Top Banner
INFORMIX-4GL SQL-Based Application Development Language for the UNIX Operating System Reference Manual INFORMIX-4GL Version4.0 March 1990 Part No. 000-7044
962
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Manual Informix

INFORMIX-4GLSQL-Based Application Development Languagefor the UNIX Operating System

Reference Manual

INFORMIX-4GLVersion4.0

March 1990Part No. 000-7044

Page 2: Manual Informix

THE INFORMIX SOFTWARE AND USER MANUAL ARE PROVIDED ‘‘AS IS’’ WITHOUTWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCEOF THE INFORMIX SOFTWARE AND USER MANUAL IS WITH YOU. SHOULD THEINFORMIX SOFTWARE AND USER MANUAL PROVE DEFECTIVE, YOU (AND NOTINFORMIX OR ANY AUTHORIZED REPRESENTATIVE OF INFORMIX) ASSUME THEENTIRE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENTWILL INFORMIX BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING ANY LOSTPROFITS, LOST SAVINGS, OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGESARISING OUT OF THE USE OF OR INABILITY TO USE SUCH INFORMIX SOFTWARE ORUSER MANUAL, EVEN IF INFORMIX OR AN AUTHORIZED REPRESENTATIVE OFINFORMIX HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANYCLAIM BY ANY OTHER PARTY. IN ADDITION, INFORMIX SHALL NOT BE LIABLE FORANY CLAIM ARISING OUT OF THE USE OF OR INABILITY TO USE SUCH INFORMIXSOFTWARE OR USER MANUAL BASED UPON STRICT LIABILITY OR INFORMIX’SNEGLIGENCE. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIEDWARRANTIES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTYGIVES 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 orused in any form or by any means—graphic, electronic, or mechanical, including photocopying,recording, taping, or information storage and retrieval systems—without permission of thepublisher.

Published by: Informix Software, Inc.4100 Bohannon DriveMenlo 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 insubdivision (b)(3)(ii) of the Rights in Technical Data and Computer Software Clause at52.227-7013 (and any other applicable license provisions set forth in the Government contract).

Copyright © 1981-1990 by Informix Software, Inc. +

ii

Page 3: Manual Informix

Table ofContents

INFORMIX-4GLReference Manual

IntroductionAbout This Manual Intro-3Related Informix Products and Documentation Intro-4Database Management Systems Intro-5

Process Architecture Intro-5Informix Database Engines Intro-6Summary of Chapters Intro-8Syntax Conventions Intro-9The Demonstration Database Intro-11

Chapter 1 Compiling 4GL Source FilesChapter Overview 1-5The Two Implementations of INFORMIX-4GL 1-5INFORMIX-4GL (C Compiler Version) 1-7The Programmer´s Environment (C Compiler Version)

1-7The INFORMIX-4GL Menu 1-8The MODULE Design Menu 1-9The FORM Design Menu 1-14The PROGRAM Design Menu 1-18The QUERY LANGUAGE Menu 1-25

Creating Executable 4GL Programs (C Compiler Version)1-25

Working in the Programmer’s Environment 1-25Working at the Command Line 1-30

Program Filename Extensions (C Compiler Version) 1-35INFORMIX-4GL (Rapid Development System) 1-36The RDS Programmer´s Environment 1-36

The INFORMIX-4GL Menu 1-37The MODULE Design Menu 1-38The FORM Design Menu 1-43

Page 4: Manual Informix

The PROGRAM Design Menu 1-48The QUERY LANGUAGE Menu 1-54

Creating Executable RDS Programs 1-54Working in the RDS Programmer’s Environment 1-54Working at the RDS Command Line 1-59

RDS Program Filename Extensions 1-72

Chapter 2 INFORMIX-4GL ProgrammingChapter Overview 2-3Language Conventions 2-3

Comments 2-3INFORMIX-4GL Identifiers 2-4Scope of Identifiers 2-4Constants 2-5

Program Variables 2-6Data Types 2-7Data Conversion 2-10Operators and Expressions 2-11Binding to Database and Forms 2-14The THRU Keyword and the .* Notation 2-15

INFORMIX-4GL Statements 2-16Variable Definition 2-17Assignment 2-17Program Organization 2-17Program Flow 2-18Screen Interaction 2-19Report Generation 2-21Error and Exception Handling 2-21Data Validation 2-23

Built-in Functions 2-24ASCII 2-25CLIPPED 2-27COLUMN 2-29CURRENT 2-30DATE 2-32DATE( ) 2-33DAY( ) 2-34EXTEND( ) 2-35LENGTH( ) 2-38MDY( ) 2-39MONTH( ) 2-40TIME 2-41TODAY 2-42

iv Table of Contents

Page 5: Manual Informix

UNITS 2-43USING 2-44WEEKDAY( ) 2-53YEAR( ) 2-54

C Functions 2-55

Chapter 3 Using SQLChapter Overview 3-5Relational Databases 3-5SQL Identifiers 3-6

Owner Naming 3-7Database Data Types 3-8SQL Statement Summary 3-10Data Definition 3-11Data Manipulation 3-12Cursor Management 3-13

SELECT Cursors 3-13INSERT Cursors 3-25

Dynamic Management 3-28Preparing Statements 3-29Executing PREPAREd Statements 3-33Preparing Multiple SQL Statements 3-38The FREE Statement 3-39

Data Access 3-40User Status and Privileges 3-41Data Integrity 3-42

Transactions 3-42Transaction Log File Maintenance 3-45Audit Trails 3-45Comparison of Transactions and Audit Trails 3-47

Locking 3-47Row-Level Locking 3-48Table-Level Locking 3-49Wait for Locked Row 3-50

Indexing Strategy 3-50Query Optimizer 3-52Auto-Indexing 3-52Clustered Indexes 3-52

NULL Values 3-53Default Values 3-54The NULL in Expressions 3-54The NULL in Boolean Expressions 3-55The NULL in WHERE Clauses 3-55

Table of Contents v

Page 6: Manual Informix

The NULL in ORDER BY Clauses 3-56The NULL in GROUP BY Clauses 3-56The NULL Keyword in INSERT and UPDATE Statements 3-57

Views 3-57Creating and Deleting Views 3-58Querying Through Views 3-58Modifying Through Views 3-59Privileges with Views 3-60Data Constraints Using Views 3-60

Outer Joins 3-61Table Access by ROWID 3-62SQLCA Record 3-63TODAY, CURRENT, and USER Functions 3-65

Chapter 4 Form Building and CompilingChapter Overview 4-3Structure of a Form Specification File 4-4

DATABASE Section 4-7SCREEN Section 4-9TABLES Section 4-15ATTRIBUTES Section 4-17AUTONEXT 4-24COLOR 4-26COMMENTS 4-28DEFAULT 4-30DISPLAY LIKE 4-32DOWNSHIFT 4-33FORMAT 4-34INCLUDE 4-36NOENTRY 4-38PICTURE 4-39REQUIRED 4-41REVERSE 4-43UPSHIFT 4-44VALIDATE LIKE 4-46VERIFY 4-47WORDWRAP 4-48INSTRUCTIONS Section 4-52Default Screen Attributes 4-57The upscol Tables in a MODE ANSI Database 4-60

Creating and Compiling a Form 4-61Through the Programmer’s Environment 4-62Through the Operating System 4-63Using PERFORM Forms in INFORMIX-4GL 4-64

vi Table of Contents

Page 7: Manual Informix

Chapter 5 Report WritingChapter Overview 5-3Calling a REPORT Routine 5-4Structure of a REPORT Routine 5-5

DEFINE Section 5-7OUTPUT Section 5-9REPORT TO 5-10LEFT MARGIN 5-12RIGHT MARGIN 5-13TOP MARGIN 5-15BOTTOM MARGIN 5-16PAGE LENGTH 5-17ORDER BY Section 5-18FORMAT Section 5-20EVERY ROW 5-21Control Blocks 5-23AFTER GROUP OF 5-25BEFORE GROUP OF 5-27FIRST PAGE HEADER 5-29ON EVERY ROW 5-31ON LAST ROW 5-33PAGE HEADER 5-34PAGE TRAILER 5-36Statements 5-37NEED 5-38PAUSE 5-39PRINT 5-40PRINT FILE 5-42SKIP 5-43Expressions and Built-in Functions 5-44Aggregates 5-46LINENO 5-48PAGENO 5-49SPACES 5-50WORDWRAP 5-51

Chapter 6 4GL Function LibraryChapter Overview 6-3The 4GL Library Functions 6-3

ARG_VAL 6-4ARR_COUNT 6-6ARR_CURR 6-7DOWNSHIFT 6-9

Table of Contents vii

Page 8: Manual Informix

ERR_GET 6-10ERR_PRINT 6-11ERR_QUIT 6-12ERRORLOG 6-13INFIELD 6-14LENGTH 6-16NUM_ARGS 6-17SCR_LINE 6-18SET_COUNT 6-20SHOWHELP 6-21STARTLOG 6-23UPSHIFT 6-25

Chapter 7 INFORMIX-4GL Statement SyntaxTypes of Statements 7-5

Statements Supported Only on INFORMIX-SE 7-6Statements Supporting INFORMIX-OnLine Enhancements 7-7INFORMIX-4GL Extensions to ANSI Syntax 7-7

Definition of Statements 7-11ALTER INDEX 7-12ALTER TABLE ( O ) 7-14BEGIN WORK 7-18CALL 7-19CASE 7-21CLEAR 7-23CLOSE 7-25CLOSE DATABASE 7-27CLOSE FORM 7-28CLOSE WINDOW 7-30COMMIT WORK 7-31CONSTRUCT 7-32CONTINUE 7-38CREATE AUDIT 7-39CREATE DATABASE ( O ) 7-41CREATE INDEX 7-44CREATE SYNONYM 7-47CREATE TABLE ( O ) 7-49CREATE VIEW 7-57CURRENT WINDOW 7-60DATABASE 7-62DECLARE 7-64DEFER 7-69DEFINE 7-71

viii Table of Contents

Page 9: Manual Informix

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

Table of Contents ix

Page 10: Manual Informix

RECOVER TABLE 7-179RENAME COLUMN 7-181RENAME TABLE 7-182REPORT 7-184RETURN 7-186REVOKE 7-187ROLLBACK WORK 7-189ROLLFORWARD DATABASE 7-190RUN 7-191SCROLL 7-192SELECT 7-193SET EXPLAIN 7-194SET LOCK MODE ( O ) 7-197SLEEP 7-199START DATABASE 7-200START REPORT 7-202UNLOAD 7-203UNLOCK TABLE 7-205UPDATE 7-206UPDATE STATISTICS 7-210VALIDATE 7-211WHENEVER 7-213WHILE 7-216

The SELECT Statement 7-218SELECT Clause 7-222INTO Clause 7-224FROM Clause 7-226WHERE Clause 7-228GROUP BY Clause 7-240HAVING Clause 7-242ORDER BY Clause 7-243INTO TEMP Clause 7-245UNION Operator 7-246

Functions in SQL Statements 7-248Aggregate Functions 7-249LENGTH( ) 7-251DATE( ) 7-252DAY( ) 7-253MDY( ) 7-254MONTH( ) 7-255WEEKDAY( ) 7-256YEAR( ) 7-257CURRENT 7-258EXTEND( ) 7-260

x Table of Contents

Page 11: Manual Informix

Appendix A Demonstration Database and Application

Appendix B System Catalogs

Appendix C Environment Variables

Appendix D Reserved Words

Appendix E INFORMIX-4GL Utility Programs

Appendix F DECIMAL Functions for C

Appendix G Outer Joins

Appendix H ASCII Character Set

Appendix I Modifying termcap and terminfo

Appendix J Working with DATETIME and INTERVAL Data

Error Messages

Index

Table of Contents xi

Page 12: Manual Informix

xii Table of Contents

Page 13: Manual Informix

Introduction

IntroductionAbout This Manual 3

Related Informix Products and Documentation 4

Database Management Systems 5Process Architecture 5

Informix Database Engines 6

Summary of Chapters 8

Syntax Conventions 9

The Demonstration Database 11

Page 14: Manual Informix

2 Introduction

Page 15: Manual Informix

About This ManualInformix Software, Inc. developed INFORMIX-4GL (Fourth-GenerationApplication Development Language) for the database designer who wantsto create custom database management applications. You can use INFOR-MIX-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 userof 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 whichsupport a similar user interface:

• The C Compiler Version, based on compiled C code, is intended primarilyfor 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 SQLand INFORMIX-4GL in stages, through example 4GL programs that increasein sophistication and subtlety.

This book, the INFORMIX-4GL Reference Manual, describes all the syntax, rules,and definitions of the variables, statements, and keywords. Another sectionof this Introduction summarizes each chapter and appendix of the ReferenceManual.

Besides these manuals, the INFORMIX-4GL Quick Reference Guide lists thedata types, operations, functions, and syntax of INFORMIX-4GL.

Introduction 3

Page 16: Manual Informix

Related Informix Products and Documentation

Related Informix Products and DocumentationThis manual assumes that you have used INFORMIX-4GL and are familiarwith the structure of relational databases. Readers with programmingexperience using INFORMIX-SQL or INFORMIX-ESQL/C will recognize oldfriends in a new setting. You can read about INFORMIX-SQL in the INFOR-MIX-SQL Reference Manual, and about INFORMIX-ESQL/C inthe INFORMIX-ESQL/C Programmer’s Manual.

The INFORMIX-4GL Interactive Debugger is a separate product designedfor use with the INFORMIX-4GL Rapid Development System. This source-language debugger is useful when you are developing or modifying 4GL pro-grams, or analyzing a 4GL program that someone else has written. TheINFORMIX-4GL Interactive Debugger is described in the Guide to theINFORMIX-4GL Interactive Debugger. Like the INFORMIX-4GL Rapid Devel-opment System, the Debugger does not require a C-compiler, unless yourapplication calls INFORMIX-ESQL/C functions or programmer-defined Cfunctions.

The underlying file and indexing structure of the database tables createdthrough INFORMIX-4GL, INFORMIX-SQL, or INFORMIX-ESQL/C is built onC-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 bibliographyon 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 directmemory access (DMA) and raw file systems. Use of the INFORMIX-OnLinedatabase engine with INFORMIX-4GL and other SQL products is described inthe INFORMIX-OnLine Programmer’s Manual. The section ‘‘Informix Data-base Engines,’’ later in this Introduction, identifies additional INFORMIX-4GLfeatures that are available only with INFORMIX-OnLine.

Note: Two files supplement the information in the manual. RELNOTES describesperformance differences from earlier versions of Informix products and how thesedifferences may affect existing applications. DOCNOTES describes feature andperformance topics not covered in the manual or modified since publication.Please examine these files as they contain vital information about applicationand performance issues. RELNOTES and DOCNOTES are located in the$INFORMIXDIR/release directory.

4 Introduction

Page 17: Manual Informix

Database Management Systems

Database Management SystemsA Database Management System (DBMS) can be divided into two parts asfollows:

• A data language, which is the user interface to the DBMS

• A database engine, which takes the data definition and data manipulationlanguage requests and performs the requested operations

Database users instruct database management systems to perform queriesand 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 thedata. These languages are often called, simply, data languages.

The DBMS must understand these languages and translate the user instruc-tions into appropriate instructions for the operating system and hardware.As a result of user instructions, the DBMS requests services such as allocationof space, storage and retrieval of blocks of data, and much more.

The database engine operates as a process, an executing program. Databaseengines serve other processes, which are database applications. These applica-tions contain the language statements that the database engine executes.

Informix products use a database definition and manipulation language thatis an extension of the ANSI standard SQL to send instructions to the databaseengine.

Process ArchitectureA database engine performs SQL operations. The database engine is a processthat handles storage and retrieval of data and other DBMS functions. The fol-lowing figure shows this implementation for products on INFORMIX-SE.

INFORMIX-4GL

INFORMIX-SE

Pipes FileAccess

Data

INFORMIX-SE

INFORMIX-SE

C-ISAM

INFORMIX-SQL

INFORMIX-ESQLIn Host Language

MULTIPLE PROCESSES

Introduction 5

Page 18: Manual Informix

Informix Database Engines

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

• With an embedded language, such as INFORMIX-ESQL/C or INFOR-MIX-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 engineprocess and the application process. While the database engine is oftenthought of as a single entity, it is actually made up of one process for eachapplication process. This one-to-one relationship between application anddatabase process allows the engine to respond immediately to a specificapplication, rather than queuing requests from all applications that need ser-vice. The database engine and application communicate using pipes.

Informix Database EnginesYou can use INFORMIX-4GL or any Informix application development toolwith either of two database engines: INFORMIX-SE or INFORMIX-OnLine.

INFORMIX-SE is based on C-ISAM, a library of C language calls that workswith UNIX to create and manipulate database files. INFORMIX-SE worksautomatically and transparently, and it does not require any special instruc-tions in your programs. Its easy setup and use make INFORMIX-SE an idealengine for developing small- to medium-size applications that do not requiremaximum performance nor an extensive range of data-integrity options.

INFORMIX-OnLine is a transaction-processing database engine that managesI/O operations directly so that performance is maximized. It is designed tohandle the high performance requirements and integrity concerns of manylarge applications. Most applications can run on either engine because fewdifferences affect the programmer. INFORMIX-OnLine, however, providesfeatures that increase performance, extend available data types, and improvethe administrative aspects of database management. The following featuresare 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 integritycontrol

6 Introduction

Page 19: Manual Informix

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 byusing direct I/O to raw storage devices, and by tuning shared memory formaximum efficiency. INFORMIX-OnLine offers high data availability, whichallows rapid recovery from system failures and provides you with loggingchoices, including the option of disk mirroring. INFORMIX-OnLine providesadvanced concurrency control by allowing you to set the level of lockinggranularity and the level of user process isolation.

INFORMIX-OnLine supports three additional data types not availablewith INFORMIX-SE. VARCHARs are variable-length character columns (upto 255 bytes) that use disk space only as it is needed. The TEXT and BYTE datatypes are Binary Large OBjects (BLOBs) capable of holding virtually any typeor amount of data. TEXT can store ASCII text files with embedded controlcharacters, such as documents generated through a word processor. BYTE canstore 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 samecomputer. You can write applications that retrieve data from multiple tables,even if the tables reside in different databases. You can use the combined datafor general display purposes or as input to a customized report.

INFORMIX-STAR is an optional add-on product to INFORMIX-OnLinethat allows you access to multiple INFORMIX-OnLine systems. With INFOR-MIX-STAR you can write queries that span multiple databases in differentINFORMIX-OnLine systems across a network.

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

Introduction 7

Page 20: Manual Informix

Summary of Chapters

Summary of ChaptersThe INFORMIX-4GL Reference Manual is divided into the following chaptersand appendices:

Introduction briefly describes the INFORMIX-4GL documentation,notational conventions used in syntax statements, andthe demonstration database.

Chapter 1 describes the C Compiler and Rapid Development Systemimplementations of INFORMIX-4GL. It also explains how tocreate executable versions of 4GL source files, both from theProgrammer’s Environment and at the command line.

Chapter 2 gives the rules for programming in INFORMIX-4GL. Itdefines data types and binding of program variables,describes expressions and functions, and explains errorhandling and the interrelationships among all the INFOR-MIX-4GL statements.

Chapter 3 describes how to interact with databases by using the Infor-mix extension to IBM’s Structured Query Language (SQL).This chapter also explains the interrelationships among var-ious types of SQL statements and illustrates the use of the4GL Programmer’s Environment.

Chapter 4 describes the procedures to construct and compile 4GLscreen form specifications.

Chapter 5 describes the procedures to specify and produce 4GLreports.

Chapter 6 describes the functions in the INFORMIX-4GL library.

8 Introduction

Page 21: Manual Informix

Syntax Conventions

Chapter 7 contains an alphabetized description of each of the SQLand INFORMIX-4GL statements that you can use in anINFORMIX-4GL program. Use this chapter as a referencefor syntax and rules concerning the use of these statements.

Appendix A describes the stores demonstration database.

Appendix B describes the system catalog tables that form the datadictionary of an INFORMIX-4GL database.

Appendix C describes the environment variables that are used by INFOR-MIX-4GL.

Appendix D lists the reserved words of INFORMIX-4GL.

Appendix E describes the bcheck, dbload, dbexport, dbimport,dbschema, dbupdate, mkmessage, sqlconv, and upscolutility programs.

Appendix F contains descriptions of C functions that handle DECIMALtype variables in C programs.

Appendix G amplifies the Chapter 3 discussion of outer joins.

Appendix H lists the ASCII characters in order.

Appendix I describes modifications that you can make to your termcapand terminfo files to extend function key definitions, tospecify characters for window borders, and to enableINFORMIX-4GL programs to interact with terminals thatsupport color displays.

Appendix J describes how you can use the DATETIME and INTERVALdata types.

Error Messages contains an extensive listing of error codes, explains theirmeaning, and suggests remedies for correcting the errors.

Index is an alphabetic list of page references for selected 4GL topicsin this manual and in its companion, the INFORMIX-4GLUser Guide.

Syntax ConventionsThis section explains how to interpret the listings of statement syntax thatappear throughout this manual.

Introduction 9

Page 22: Manual Informix

Syntax Conventions

ABC Enter any term that appears in uppercase letters exactly as shown,disregarding case. Such terms are ‘‘keywords.’’ For example,

CREATE INDEX indnamemeans you must enter CREATE INDEX or create index withoutadding 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. Ineach 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 state-ment, 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 exam-ple,

CREATE [ UNIQUE ] INDEX

indicates that you can enter either CREATE INDEX or CREATEUNIQUE INDEX.

| Select one of the options shown. The vertical bar indicates a choiceamong several options. For example,

[ ONE | TWO [ THREE ] | FOUR ]

means that you can enter ONEor TWOor FOUR , and that, if you enterTWO, you can also enter THREE. (Because all the choices are enclosedin square brackets, you can also choose to omit them completely.)

{ } Choose one of the listed options. When the options are enclosed inbraces and separated by vertical bars, you must select one of theoptions. For example,

{ ONE | TWO | THREE }

means that you must enter ONE or TWOor THREE, and that you can-not enter more than one selection. Unless advised otherwise, do notenter braces in a statement.

ABC Omit or use an option that is underlined. When one of several optionsis 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 donot enter any of them, VANILLA is the default.

10 Introduction

Page 23: Manual Informix

The Demonstration Database

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

statement. . .

means that there can be a series of statements following the one thatis 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 , exactlyas they appear in the syntax statement.

The notation ‘‘(O)’’ sometimes follows the name of a statement at the begin-ning of a syntax description in Chapter 7. This means that additional optionsor features are supported by INFORMIX-4GL on the INFORMIX-OnLine data-base engine. Refer to the INFORMIX-OnLine Programmer’s Manual for detailsof the additional functionality available with INFORMIX-OnLine.

The Demonstration DatabaseMost of the examples in this manual are based on the stores demonstrationdatabase. This database, which is described and listed in detail inAppendix A, involves a wholesale sporting goods firm that maintains a stockof 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 DevelopmentSystem).

Each shell script removes any database labeled stores and installs the dem-onstration database.

The stores database contains six tables:

customer contains information about the retail stores that purchasesporting supplies.

orders contains information about the individual orders from theretail stores.

items contains information about the items in an order.

stock contains information about the variety of sporting goodsavailable.

Introduction 11

Page 24: Manual Informix

The Demonstration Database

manufact contains information about manufacturers of sportinggoods.

state contains the names and abbreviations of U.S. states.

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

12 Introduction

Page 25: Manual Informix

Chapter

1

Compiling 4GLSource FilesChapter Overview 5

The Two Implementations of INFORMIX-4GL 5

INFORMIX-4GL (C Compiler Version) 7

The Programmer´s Environment (C Compiler Version) 7The INFORMIX-4GL Menu 8The MODULE Design Menu 9

The Modify Option 9The New Option 12The Compile Option 12The Program_Compile Option 13The Run Option 13The Exit Option 14

The FORM Design Menu 14The Modify Option 15The Generate Option 16The New Option 17The Compile Option 17The Exit Option 18

The PROGRAM Design Menu 18The Modify Option 19The New Option 22The Compile Option 22The Planned_Compile Option 23The Run Option 24The Drop Option 24The Exit Option 24

The QUERY LANGUAGE Menu 25

Page 26: Manual Informix

Creating Executable 4GL Programs (C Compiler Version) 25Working in the Programmer’s Environment 25

Creating a New Source Module 26Revising an Existing Module 26Compiling a Source Module 27Linking Program Modules 28Executing a Compiled Program 30

Working at the Command Line 30Creating or Modifying a 4GL Source File 31Compiling a 4GL Module 31Compiling and Linking Multiple Source Files 32Running 4GL Programs 344GL Programs That Call C Functions 34

Program Filename Extensions (C Compiler Version) 35

INFORMIX-4GL (Rapid Development System) 36

The RDS Programmer´s Environment 36The INFORMIX-4GL Menu 37The MODULE Design Menu 38

The Modify Option 39The New Option 41The Compile Option 41The Program_Compile Option 41The Run Option 42The Debug Option 42The Exit Option 43

The FORM Design Menu 43The Modify Option 44The Generate Option 46The New Option 46The Compile Option 47The Exit Option 47

The PROGRAM Design Menu 48The Modify Option 49The New Option 51The Compile Option 51The Planned_Compile Option 52The Run Option 52The Debug Option 53The Undefine Option 53The Exit Option 53

The QUERY LANGUAGE Menu 54

1-2 Compiling 4GL Source Files

Page 27: Manual Informix

Creating Executable RDS Programs 54Working in the RDS Programmer’s Environment 54

Creating a New Source Module 55Revising an Existing Module 55Compiling a Source Module 56Combining Program Modules 57Executing a Compiled RDS Program 58Invoking the Debugger 59

Working at the RDS Command Line 59Creating or Modifying a 4GL Source File 61Compiling an RDS Source File 61Concatenating Multi-Module Programs 63Running RDS Programs 64Running Multi-Module Programs 65Running Programs with the Interactive Debugger 65RDS Programs That Call C Functions 66Editing the fgiusr.c File 67Creating a Customized Runner 69Running Programs That Call C Functions 72

RDS Program Filename Extensions 72

Compiling 4GL Source Files 1-3

Page 28: Manual Informix

1-4 Compiling 4GL Source Files

Page 29: Manual Informix

Chapter OverviewThis chapter describes how to create INFORMIX-4GL source-code modules,and how to produce executable 4GL programs from these source-codemodules, both at the operating system prompt and from within the INFOR-MIX-4GL Programmer’s Environment.

The procedures to do this are described for the INFORMIX-4GL C CompilerVersion, as well as for the INFORMIX-4GL Rapid Development System.These two implementations of INFORMIX-4GL differ in how they process4GL source-code modules.

The Two Implementations of INFORMIX-4GLTo write an INFORMIX-4GL program, you must first create an ASCII fileof 4GL statements that perform logical tasks to support your application.Other chapters and appendixes describe the features of the INFORMIX-4GLapplication development language, and the use and syntax of its statementsand utilities. This chapter explains the procedures by which you cantransform one or more source-code files of INFORMIX-4GL statements intoan executable 4GL program.

Informix Software, Inc., offers two different implementations of the INFOR-MIX-4GL application development language:

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

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

Compiling 4GL Source Files 1-5

Page 30: Manual Informix

The Two Implementations of INFORMIX-4GL

Both implementations use the same INFORMIX-4GL statements, and nearlyidentical Programmer’s Environments. Because they use different methodsto compile your 4GL source files into executable programs, however, there area few differences in the user interfaces.

These differences are summarized on this page and the next:

• Differences in Command Lines

Compiler RDS Effect of Commandi4gl r4gl Enter Programmer’s Environmentc4gl sfile.4gl fglpc sfile Compile 4GL source file sfile.4glxfile.4ge fglgo xfile Execute compiled 4GL program xfilei4gldemo r4gldemo Create the demonstration database

The INFORMIX-4GL C Compiler Version requires no equivalent to thefglgo command, since its compiled object files are executable without arunner. The INFORMIX-4GL Rapid Development System also contains acommand-file script to compile and execute 4GL programs that call Cfunctions or INFORMIX-ESQL/C functions, as described near the end ofthis chapter.

• Differences in the Programmer’s Environment

The Programmer’s Environment is a system of menus that supports thevarious steps in the process of developing 4GL application programs. TheDrop option on the PROGRAM Design Menu of the C Compiler Version iscalled Undefine in the INFORMIX-4GL Rapid Development Systemimplementation.

The New and Modify options of the PROGRAM Design Menu display adifferent screen form in the two implementations. Both of these screenforms are illustrated later in this chapter.

The INFORMIX-4GL Rapid Development System includes a Debugoption on its MODULE Design Menu and PROGRAM Design Menu. Thisoption does not appear in the C Compiler Version. (The Debugger isbased on p-code, so it can execute programs and modules compiled bythe INFORMIX-4GL Rapid Development System).

The INFORMIX-4GL Interactive Debugger is available as a separateproduct.

• Differences in Filename Extensions

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

The backup file extensions .4bo and .4be for compiled modules andprograms have the same names in both implementations. These

1-6 Compiling 4GL Source Files

Page 31: Manual Informix

INFORMIX-4GL (C Compiler Version)

designate files that are not interchangeable between the two 4GL imple-mentations, however, because object code produced by a C compiler isdifferent from p-code.

Other filename extensions that are the same in both the C Compiler Ver-sion and Rapid Development System Version designate interchangeablefiles, if you use both implementations of INFORMIX-4GL to process thesame 4GL source-code module.

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

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

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

• It describes the equivalent command-line syntax for compiling andexecuting 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 theINFORMIX-4GL Rapid Development System, skip ahead to the section enti-tled “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 4GLprogram development and keep track of the components of your application.You can invoke the Programmer’s Environment by entering i4gl at thesystem prompt.

Compiling 4GL Source Files 1-7

Page 32: Manual Informix

The INFORMIX-4GL Menu

The INFORMIX-4GL MenuThe i4gl command briefly displays the INFORMIX-4GL banner. Then amenu appears, called the INFORMIX-4GL Menu:

INFORMIX-4GL: Module Form Program Query-language ExitCreate, 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 theProgrammer’s Environment. You have five options:

Module Work on an INFORMIX-4GL program module.

Form Work on a screen form.

Program Specify components of a multi-module program.

Query-language Use the SQL interactive interface, if you have INFOR-MIX-SQL installed on your system.

Exit Return to the operating system.

The first three options display new menus that are described in the pages thatfollow. (You can also press CTRL-W at any menu to display an on-line helpmessage that describes your options.) As at any 4GL menu, you can select anoption 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 optionthat you choose, and then pressing RETURN.

1-8 Compiling 4GL Source Files

Page 33: Manual Informix

The MODULE Design Menu

The MODULE Design MenuYou can press RETURN or type m or M to select the Module option of theINFORMIX-4GL Menu. This displays a new menu, called the MODULE DesignMenu. Use this menu to work on an individual 4GL source-code module.

MODULE: Modify New Compile Program_Compile Run ExitChange an existing 4GL program module.

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

The MODULE Design Menu supports the following options:

Modify Change an existing 4GL source-code module.

New Create a new 4GL source-code module.

Compile Compile a 4GL source-code module.

Program_Compile Compile a 4GL application program.

Run Execute a compiled 4GL program module or a multi-module application program.

Exit Return to the INFORMIX-4GL Menu.

As in all of the menus of the Programmer’s Environment except the INFOR-MIX-4GL Menu, the Exit option returns control to the higher menu fromwhich you accessed the current menu.

You can use these options to create and compile source-code modules ofa 4GL application. See “The FORM Design Menu” later in this chapter forinformation on creating 4GL screen forms. See also “The mkmessage Utility”section in Appendix E for information on how to create and compileprogrammer-defined help messages for an INFORMIX-4GL application.

The Modify Option

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

Compiling 4GL Source Files 1-9

Page 34: Manual Informix

The MODULE Design Menu

(see Appendix C) or named an editor previously in this session at theProgrammer’s Environment, INFORMIX-4GL invokes that editor. The 4GLsource file whose filename you specified is the current file.

When you leave the editor, INFORMIX-4GL displays the MODIFY MODULEMenu, with the Compile option highlighted:

MODIFY MODULE: Compile Save-and-exit Discard-and-exitCompile the 4GL module specification.

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

If you press RETURN or type c or C to select the Compile option, INFOR-MIX-4GL displays the COMPILE MODULE Menu:

COMPILE MODULE: Object Runable ExitCreate 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 noattempt to link the file with other files.

The Runable option creates a compiled file with the .4ge extension. INFOR-MIX-4GL assumes that the current module is a complete 4GL program, andthat no other module needs to be linked to it. Select the Runable option if thecurrent 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 youmust use the PROGRAM Design menu to specify all the component modules.

After you select Object or Runable, a message near the bottom of the screenwill advise you if INFORMIX-4GL issues a compile-time warning or error. Ifthere are warnings (but no errors), an executable file is produced. Select the

1-10 Compiling 4GL Source Files

Page 35: Manual Informix

The MODULE Design Menu

Exit option of the next menu, and then Save-and-exit at the MODIFYMODULE Menu, if you want to save the executable file without reading thewarnings.

Alternatively, you can examine the warning messages by selecting Correct atthe next menu. When you finish editing the .err file that contains the warn-ings, you must select Compile again from the MODIFY MODULE Menu, sincethe Correct option deletes the executable file.

If there are compilation errors, the following menu appears:

COMPILE MODULE: Correct ExitCorrect 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 yoursource module with embedded error messages. You do not need to delete theerror messages, since INFORMIX-4GL does this for you. Correct your sourcefile, save your changes, and exit from the editor. The MODIFY MODULE Menureappears, prompting you to recompile, or to save or discard your changeswithout compiling.

If there are no compilation errors, the MODIFY MODULE Menu appears withthe Save-and-Exit option highlighted. Select this option to save the currentsource-code module as a file with extension .4gl, and create an object file withthe same filename, but with the extension .o. If you specified Runable whenyou compiled, the executable version is saved with the extension .4ge. TheDiscard-and-Exit option discards any changes to your file since you selectedthe Modify option.

Compiling 4GL Source Files 1-11

Page 36: Manual Informix

The MODULE Design Menu

The New Option

Select this option to create a new 4GL source-code module.

MODULE: Modify New Compile Program_Compile Run ExitCreate a new 4GL program module.

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

This option resembles the Modify option, but NEW MODULE is the menutitle, 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 withDBEDIT, 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-codemodule without first selecting the Modify option.

MODULE: Modify New Compile Program_Compile Run ExitCompile an existing 4GL program module.

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

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

1-12 Compiling 4GL Source Files

Page 37: Manual Informix

The MODULE Design Menu

The Program_Compile Option

The Program_Compile option of the MODULE Design Menu is the same asthe Compile option of the PROGRAM Design Menu. (See that option fordetails.) You can use this option to compile and link modules, as described inthe program specification database, taking into account the time when themodules were last updated.

This option is useful when you have just modified a single module of a com-plex program, and need to test it by compiling and linking it with the othermodules.

The Run Option

Select this option to begin execution of a compiled program.

MODULE: Modify New Compile Program_Compile Run ExitExecute an existing 4GL program module or application program.

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

The RUN PROGRAM screen presents a list of compiled modules and pro-grams, with the highlight on the module corresponding to the current file, ifany has been specified. Compiled programs must have the extension .4ge tobe included in the list. If you compile a program outside the Programmer’sEnvironment and you want it to appear in the program list, give it the exten-sion .4ge. If no compiled programs exist, INFORMIX-4GL displays an errormessage and restores the MODULE Design Menu.

Compiling 4GL Source Files 1-13

Page 38: Manual Informix

The FORM Design Menu

The Exit Option

Select this option to exit from the MODULE Design Menu and display theINFORMIX-4GL Menu.

MODULE: Modify New Compile Program_Compile Run ExitReturns to the INFORMIX-4GL Menu.

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

The FORM Design MenuYou 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 ExitChange an existing form specification.

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

You can use this menu to create, modify, and compile screen form specifica-tions. These define visual displays that 4GL applications can use to query andmodify the information in a database. INFORMIX-4GL form specification filesare ASCII files that are described in Chapter 4 of this manual, and inChapters 6 and 7 of the INFORMIX-4GL User Guide.

The FORM Design Menu supports the following options:

Modify Change an existing 4GL screen form specification.

Generate Create a default 4GL screen form specification.

New Create a new 4GL screen form specification.

Compile Compile an existing 4GL screen form specification.

Exit Return to the INFORMIX-4GL Menu.

1-14 Compiling 4GL Source Files

Page 39: Manual Informix

The FORM Design Menu

Readers familiar with INFORMIX-SQL may notice that this resembles themenu 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 existingform specification file. It resembles the Modify option in the MODULE DesignMenu, since both options are used to edit program modules.

FORM: Modify Generate New Compile ExitChange an existing form specification.

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

If you select this option, you are prompted to select the name of a formspecification file to modify. Source files created at the FORM Design Menuhave the file extension .per. (If you use a text editor outside of the Program-mer’s Environment to create form specification files, you must give them theextension .per before you can compile them with the FORM4GL screen formfacility.)

If you have not already designated a text editor in this INFORMIX-4GLsession or with DBEDIT, you are prompted for the name of an editor. Then anediting session begins, with the form specification source-code file that youspecified as the current file. When you leave the editor, INFORMIX-4GLdisplays 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 Discard-and-exitCompile the form specification.

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

Compiling 4GL Source Files 1-15

Page 40: Manual Informix

The FORM Design Menu

If there are compilation errors, INFORMIX-4GL displays the COMPILE FORMMenu:

COMPILE FORM: Correct ExitCorrect errors in the form specification.

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

Press RETURN to select Correct as your option. An editing session begins ona copy of the current form, with diagnostic error messages embedded wherethe compiler detected syntax errors. INFORMIX-4GL automatically deletesthese messages when you save and exit from the editor. After you have cor-rected the errors, the MODIFY FORM Menu appears again, with the Compileoption highlighted. Press RETURN to recompile. Repeat these steps until thecompiler reports no errors.

If there are no compilation errors, you are prompted whether to savethe modified form specification file and the compiled form, or to discardthe changes. (Discarding the changes restores the version of your formspecifications from before you chose the Modify option.)

The Generate Option

You can type g or G to select the Generate option. This option creates asimple ‘‘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 ExitGenerate and compile a default form specification.

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

1-16 Compiling 4GL Source Files

Page 41: Manual Informix

The FORM Design Menu

When you select this option, INFORMIX-4GL prompts you to select a data-base, to choose a filename for the form specification, and to identify the tablesthat the form will access. After you provide these data, INFORMIX-4GL cre-ates and compiles a form specification file. (This is equivalent to runningthe -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 newscreen form specification.

FORM: Modify Generate New Compile ExitCreate a new form specification.

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

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

The Compile Option

The Compile option enables you to compile an existing form specificationfile without going through the Modify option.

FORM: Modify Generate New Compile ExitCompile an existing form specification.

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

Compiling 4GL Source Files 1-17

Page 42: Manual Informix

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 Menuwith the highlight on the Correct option.

The Exit Option

The Exit option restores the INFORMIX-4GL Menu.

FORM: Modify Generate New Compile ExitReturns to the INFORMIX-4GL Menu.

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

The PROGRAM Design MenuAn INFORMIX-4GL program can be a single source-code module that youcreate and compile at the MODULE Design Menu. For applications of greatercomplexity, however, it is often easier to develop and maintain separate 4GLmodules. The INFORMIX-4GL Menu includes the Program option so that youcan create multi-module programs. If you select this option, INFORMIX-4GLsearches your DBPATH directories (see Appendix C) for the program specifi-cation database, called syspgm4gl. This database describes the componentmodules and function libraries of your 4GL program.

If INFORMIX-4GL cannot find this database, you are asked if you want onecreated. If you enter y in response, INFORMIX-4GL creates the syspgm4gldatabase, grants CONNECT privilege to PUBLIC, and displays the PROGRAMDesign Menu. As Database Administrator of syspgm4gl, you can laterrestrict the access of other users.

1-18 Compiling 4GL Source Files

Page 43: Manual Informix

The PROGRAM Design Menu

If syspgm4gl already exists, the PROGRAM Design Menu appears.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitChange 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 spec-ification, to compile and link a program, or to execute a program.

The PROGRAM Design Menu supports the following options:

Modify Change an existing program specification.

New Create a new program specification.

Compile Compile an existing program.

Planned_Compile List the steps necessary to compile and link an existingprogram.

Run Execute an existing program.

Drop Delete an existing program specification.

Exit Return to the INFORMIX-4GL Menu.

You must first use the MODULE Design Menu and FORM Design Menu toenter and edit the INFORMIX-4GL statements within the component source-code modules of a 4GL program. Then you can use the PROGRAM DesignMenu 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 4GLprogram. (This option is not valid unless at least one program has alreadybeen specified. If none has, you can create a program specification by select-ing the New option from the same menu.) INFORMIX-4GL prompts you for

Compiling 4GL Source Files 1-19

Page 44: Manual Informix

The PROGRAM Design Menu

the name of the program specification to be modified. It then displays a menuand form that you can use to update the information in the program specifi-cation database as shown in Figure 1-1:

MODIFY PROGRAM: 4GL Other Libraries Compile_Options Rename ExitEdit the 4GL sources list.

-------------------------------------------------Press CTRL-W for Help------Program[myprog ]

4gl Source 4gl Source Path[main ] [/u/john/appl/4GL ][funct ] [/u/john/appl/4GL ][rept ] [/u/john/appl/4GL ][ ] [ ][ ] [ ]

Other Source Ext Other Source Path[cfunc ] [c ] [/u/john/appl/C ][ ] [ ] [ ][ ] [ ] [ ][ ] [ ] [ ]

Libraries [m ] Compile Options [ ][ ] [ ]

Figure 1-1 Example of a Program Specification Entry

The name of the program appears in the Program field. In Figure 1-1 the nameis myprog. You can change this name by selecting the Rename option.INFORMIX-4GL assigns the program name, with the extension .4ge, to theexecutable program produced by compiling and linking all the source filesand libraries. (Compiling and linking occurs when you select the Compileoption, as described later in this chapter.) In this example, the resulting exe-cutable program would have the name myprog.4ge.

Use the 4GL option to update the entries for the 4GL Source fields and the 4GLSource Path fields on the form. The five rows of fields under these labels forma screen array. When you select the 4GL option, INFORMIX-4GL executes anINPUT ARRAY statement so you can move and scroll through the array. Seethe INPUT ARRAY statement in Chapter 7 for information about how to useyour function keys to scroll, delete rows, and insert new rows. (You cannotredefine the function keys, however, as you can with an INFORMIX-4GLprogram.)

1-20 Compiling 4GL Source Files

Page 45: Manual Informix

The PROGRAM Design Menu

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

• 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 modulesor object-code modules in your program. Enter this information intothe three-column screen array with the headings Other Source, Ext, and OtherSource Path. Enter the filename and location of each non-INFORMIX-4GLsource-code or object-code module in these fields. Enter the name of themodule in the Other Source field, the filename extension of the module (forexample, ec for an INFORMIX-ESQL/C module, or c for a C module) in theExt field, and the full directory path of the module in the Other Source Pathfield. The example in Figure 1-1 includes a file containing C function source-code (cfunc.c) located in /u/john/appl/C. You can list up to 100 files in thisarray.

The Libraries option enables you to indicate the names of up to ten speciallibraries to link with your program. INFORMIX-4GL calls the C compiler todo the linking and adds the appropriate -l prefix, so you should enter onlywhat follows the prefix. The example displayed in Figure 1-1 calls only thestandard 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 atthe Command Line” for more information about the options of the c4glcommand).

The Exit option exits from the MODIFY PROGRAM Menu and displays thePROGRAM Design Menu.

Compiling 4GL Source Files 1-21

Page 46: Manual Informix

The PROGRAM Design Menu

The New Option

Use the New option on the PROGRAM Design Menu to create a new specifi-cation of the program modules and libraries that make up an application pro-gram. You can also specify any necessary compiler or loader options.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitAdd 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 ofthe PROGRAM Design Menu are identical, except that you must first supplya name for your program when you select the New option. (INFORMIX-4GLdisplays a blank form in the NEW PROGRAM Menu.) The NEW PROGRAMMenu has the same options as the MODIFY PROGRAM Menu, as illustratedearlier.

The Compile Option

The Compile option performs the compilation and linking described in theprogram specification database, taking into account the time when each filewas last updated. It compiles only those files that have not been compiledsince they were changed.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitCompile a 4GL application program.

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

INFORMIX-4GL lists each step of the preprocessing and compilation as itoccurs. An example of these messages appears in the illustration of ‘‘ThePlanned_Compile Option’’ in the next section.

1-22 Compiling 4GL Source Files

Page 47: Manual Informix

The PROGRAM Design Menu

The Planned_Compile Option

Taking into account the time when the various files in the dependencyrelationships last changed, the Planned_Compile option prompts for aprogram name and displays a summary of the steps that will be executedif you select the Compile option. No compilation actually takes place.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitShow 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:

mCompiling/Linking other sources:

/u/john/appl/C/cfunc.c

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

Compiling 4GL Source Files 1-23

Page 48: Manual Informix

The PROGRAM Design Menu

The Run Option

The Run option of the PROGRAM Design Menu is the same as the Run optionof the MODULE Design Menu. It displays a list of any compiled programs(files with the extension .4ge) and positions the highlight on the currentprogram, if a program has been specified. INFORMIX-4GL then executes theprogram that you select.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitExecute a 4GL application program

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

The Drop Option

The Drop option of the PROGRAM Design Menu prompts you for a programname and removes the compilation and linking definition of that programfrom the syspgm4gl database. This action removes the definition only. Yourprogram and 4GL modules are not removed.

PROGRAM: Modify New Compile Planned_Compile Run Drop ExitDrop 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 INFOR-MIX-4GL Menu.

1-24 Compiling 4GL Source Files

Page 49: Manual Informix

The QUERY LANGUAGE Menu

The QUERY LANGUAGE MenuThe SQL interactive interface is identical to the interactive SQL interfaceof INFORMIX-SQL. You can use this option only if you have separatelypurchased INFORMIX-SQL and installed it.

The Query-language option is placed at the top-level menu so you can testSQL statements without leaving the INFORMIX-4GL Programmer’s Environ-ment. 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-4GLrequires 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 addi-tional libraries whose functions are called.

The sections that follow describe how to carry out these steps, both from theProgrammer’s Environment and at the system prompt.

Working in the Programmer’s EnvironmentIf your software has been installed according to the instructions in yourInstallation Guide, you can enter

i4gl

at the system prompt to invoke the Programmer’s Environment. Aftera pause for the sign-on message, the INFORMIX-4GL Menu appears.

Compiling 4GL Source Files 1-25

Page 50: Manual Informix

Working in the Programmer’s Environment

Creating a New Source Module

This section outlines the procedure for creating a new module. If your sourcemodule already exists but needs to be modified, you should skip ahead to thenext 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 Newoption of the MODULE Design Menu. The screen prompts you for a nameto assign to the new module.

• Enter a name for the new module. The name must begin with a letter andcan include letters, numbers, and underscores. The name must be uniqueamong the files in the same directory, and among the other program mod-ules, if it will be part of a multi-module program. INFORMIX-4GL attachesextension .4gl to this identifier, as the filename of your new sourcemodule.

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 stepsthat 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 currentdirectory and prompts you to select a source file to edit. Use the Arrowkeys to highlight the name of a source module and press RETURN, orenter 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, thescreen prompts you to specify a text editor.

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

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

1-26 Compiling 4GL Source Files

Page 51: Manual Informix

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 mustbe compiled before it can be executed. After you save your file and exit fromthe 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 selectCompile, the screen prompts you to select among three options:Object, Runable, and Exit.

What you should do depends on whether your module is a completeprogram, or whether it is one of several .4gl modules that togethercomprise 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 versionof your source-code module, then calls the ESQL/C preprocessor whichproduces C output, and finally calls the C compiler to produce a compiledfile with the same filename, but with the extension .4ge.

• If the module is one module of a multi-module 4GL program, selectObject. This option creates a compiled object file module, with the samefilename, but with extension .o. See also the procedures for linking pro-gram modules, which are described later in this section.

If the compiler detects errors after either option, no compiled file is cre-ated, and the screen prompts you to select Correct or Exit. Follow the firsttwo steps on the next page after an error.

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

• Edit the file to correct the error, and select Compile again. If an error mes-sage appears, repeat the previous steps, until the module compileswithout error.

• After the module compiles successfully, the screen prompts you again toCompile, or to Save-and-exit, or to Discard-and-exit. Select the secondoption, to save the compiled program. The MODULE Design Menuappears again on your screen.

• If your program requires screen forms, you must select Exit to return to theINFORMIX-4GL Menu, and then select Form to display the FORM DesignMenu. See Chapter 4 for information about designing and creating screenforms.

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

Compiling 4GL Source Files 1-27

Page 52: Manual Informix

Working in the Programmer’s Environment

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

Linking Program Modules

If the module that you compiled is the only module in your program, you arenow ready to run your program, and you can skip the steps that are describedhere. 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 beforeyou can run the program.

• If you are not at the INFORMIX-4GL Menu, select Exit until that menuappears. Then select the Program option, to display the PROGRAMDesign Menu.

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

• Enter the name (without a file extension) of the program that you aremodifying, or the name to be assigned to a new program. Names mustbegin with a letter, and can include letters, underscores ( _ ), and numbers.After you enter a valid name, the PROGRAM screen appears, with yourprogram name in the first field.

If you selected Modify, the names and pathnames of the source-codemodules are also displayed. In that case, the PROGRAM screen appearsbelow the MODIFY PROGRAM Menu, rather than below the NEWPROGRAM Menu. (Both menus list the same options.)

1-28 Compiling 4GL Source Files

Page 53: Manual Informix

Working in the Programmer’s Environment

• To specify new 4GL modules or edit the list of 4GL modules, pressRETURN to select the 4GL option. You can enter or edit the name of amodule, 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 bythe DBPATH environment variable, enter the pathname to the directorywhere the module resides.

• If your program includes any modules that are not 4GL source files, youshould select the Other option. This option enables you to specify eachfilename 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’’ mod-ules, such as C language source files or object files. If you have the INFOR-MIX-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), selectthe Libraries option. This option enables you to enter or edit the list oflibrary 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, selectthe Exit option to return to the PROGRAM Design Menu.

MODIFY PROGRAM: 4GL Other Libraries Compile_Options Rename ExitEdit the 4GL sources list.-------------------------------------------------Press CTRL-W for Help------

Program[ ]

4gl Source 4gl Source Path[ ] [ ][ ] [ ][ ] [ ][ ] [ ][ ] [ ]

Other Source Ext Other Source Path[ ] [ ] [ ][ ] [ ] [ ][ ] [ ] [ ][ ] [ ] [ ]

Libraries [ ] Compile Options [ ][ ] [ ]

Compiling 4GL Source Files 1-29

Page 54: Manual Informix

Working at the Command Line

• Select the Compile option of the PROGRAM Design Menu. This optionproduces 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 thePROGRAM 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 pro-duced automatically when you work at the Programmer’s Environmentof the INFORMIX-4GL C Compiler Version.

Executing a Compiled Program

After compiling and linking your program modules, you can type r or R orpress RETURN to select the Run option. This option begins execution of thecompiled 4GL program. Your program can display menus, screen forms, win-dows, or other screen output according to your program logic and your key-board interaction with the program.

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

Figure 1-2 Creating and Running an INFORMIX-4GL Program

TEXTEDITOR

.4glSourceFiles

.o ObjectFiles

PREPROCESSOR& COMPILER

c4gl

.c, .ecFiles

.4geCompiledProgram

File

.errErrorFile

1-30 Compiling 4GL Source Files

Page 55: Manual Informix

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 asinput 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), andobject files (.o).

• The program module can then be compiled, by invoking the c4gl prepro-cessor and compiler command. (If error messages result, find them in the.err file and edit the source file to correct the errors. Then recompile thecorrected source module.)

The resulting compiled .4ge program file is an executable command filethat 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 Program-mer’s Environment is summarized by the following list:

Command Invokes Menu Optionvi UNIX System Editor Module New/Modifyc4gl 4GL Preprocessor/Compiler Compilefilename.4ge 4GL Application Run

Creating or Modifying a 4GL Source File

Use your system editor or another text editing program to create a .4gl sourcefile or to modify an existing file. See the documentation of your text editorand the other chapters of this manual for details.

Compiling a 4GL Module

You can compile an INFORMIX-4GL source file at the system prompt byentering a command of the form:

c4gl source. 4gl -o filename.4ge

Compiling 4GL Source Files 1-31

Page 56: Manual Informix

Working at the Command Line

The c4gl command compiles your 4GL source-code module (here calledsource.4gl) and produces an executable program called filename.4ge. The com-plete 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. Youcannot execute a 4GL program until you have preprocessed and compiled allthe source modules and linked them with any function libraries that they ref-erence. You can do all this in a single step at the system prompt by the c4glcommand, which performs the following processing steps:

1. Reads your 4GL source-code files (extension .4gl) and preprocesses themto 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 addi-tional libraries that you specify in the command line.

You must assign the filename extension .4gl to any INFORMIX-4GL source-code modules that you compile. The resulting .4ge file is an executable ver-sion of your program.

Notice that ESQL/C source files (with extension .ec), C source files (withextension .c), and C object files (with extension .o) are intermediate steps inproducing an executable INFORMIX-4GL program. Besides 4GL source files(with extension .4gl), you can also include files of any or all of these typeswhen you specify a c4gl command line to compile and link the componentmodules 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 displays the release version number of your SQL software,without processing any source files.

-ansi instructs the compiler to check all SQL statements for com-pliance with ANSI standards.

1-32 Compiling 4GL Source Files

Page 57: Manual Informix

Working at the Command Line

-e performs only the preprocessor steps, with no compilationor linking.

-a causes your compiled program to check array bounds at runtime. The -a option must appear on the command line beforethe source.4gl filename.

-otherargs are other arguments for your C compiler.

outfile is a name that you assign to the compiled 4GL program.

source.4gl is the name of an INFORMIX-4GL source module. You mustspecify the .4gl extension.

otheresql.ec is an ESQL/C source file to compile and link.

othersrc.c is a C language source file to compile and link.

otherobj.o is an object file to link with your 4GL program.

yourlib is a library from which to extract functions that are not partof the INFORMIX-4GL or INFORMIX-ESQL/C libraries.

Notes

1. If you specify the -V option to display the version number, all otherarguments are ignored, and no output files are produced.

2. Since the -a option requires additional run-time processing, you maywant to use this option only during development to debug your program.

3. The c4gl command passes all C compiler arguments (otherargs) and otherC source and object files (othersrc.c, otherobj.o) directly to the C compiler(cc).

4. You can compile INFORMIX-4GL modules separately from your MAINprogram block. If there is no MAIN program block in source.4gl, your codeis 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 MAINprogram block at another time. (Chapter 2 of the INFORMIX-4GL UserGuide describes the MAIN program block.)

5. If you specify the -ansi option, it must appear first in your list of c4glcommand arguments. The -ansi option asks for compile-time warningmessages if your source code includes Informix extensions to the ANSIstandard for SQL. (Chapter 7 lists the Informix syntax extensions.) Com-piler 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

Page 58: Manual Informix

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 previ-ously compiled INFORMIX-4GL modules, and mod4.4gl is a source-codemodule. Suppose that you want to compile and link mod4.4gl with the threeobject 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 .4gefile (or whatever you specify after the -o argument) that is an executablecommand file.

To execute your compiled INFORMIX-4GL application program, enter thefilename at the system prompt. For example, to run myappl.4ge (the programin the previous example), simply enter the command line:

myappl.4ge

(Some INFORMIX-4GL programs may require additional command-linearguments, such as constants or filenames, depending on the logic of yourspecific 4GL application.)

4GL Programs That Call C Functions

No special procedures are needed to create, compile, and execute 4GLprograms that call C functions or INFORMIX-ESQL/C functions when youuse the C Compiler Version of INFORMIX-4GL. See, however, the section “CFunctions” in Chapter 2 for details of creating INFORMIX-4GL programs thatcall programmer-defined C functions within 4GL modules. See alsoAppendix F, “DECIMAL Functions for C,” which addresses issues of dataconversion.

1-34 Compiling 4GL Source Files

Page 59: Manual Informix

Program Filename Extensions (C Compiler Version)

Program Filename Extensions (C Compiler Version)Source, runable, error, and backup files generated by INFORMIX-4GL arestored in the current directory and are labeled with a filename extension. Thefollowing list shows the file extensions for the source, runable, and error files.These files are produced during the normal course of using the C CompilerVersion of INFORMIX-4GL.

file.4gl is an INFORMIX-4GL source file.

file.o is an INFORMIX-4GL object file.

file.4ge is an INFORMIX-4GL executable (runable) file.

file.err is an INFORMIX-4GL source error file, created when anattempt to compile a module fails. The file contains INFOR-MIX-4GL source code, plus any compiler syntax error orwarning messages.

file.ec is an intermediate source file, created during the normalcourse of compiling an INFORMIX-4GL module.

file.c is an intermediate C file, created during the normal course ofcompiling an INFORMIX-4GL module.

file.erc is an INFORMIX-4GL object error file, created when anattempt to compile or to link a non-INFORMIX-4GL source-code or object module fails. The file contains INFORMIX-4GLsource code and annotated compiler errors.

form.per is a FORM4GL source file.

form.frm is a FORM4GL object file.

form.err is a FORM4GL source error file.

The last three files do not exist unless you create or modify a screen formspecification file, as described in Chapter 4.

The next page lists the corresponding file extensions for the backup filesthat INFORMIX-4GL automatically creates when you use the Programmer’sEnvironment to process 4GL source files.

The following list identifies the backup files that are produced when you useINFORMIX-4GL from the Programmer’s Environment.

file.4bl is an INFORMIX-4GL source backup file, created during themodification and compilation of a .4gl program module.

file.4bo is an object backup file, created during the compilation ofa .o program module.

Compiling 4GL Source Files 1-35

Page 60: Manual Informix

INFORMIX-4GL (Rapid Development System)

file.4be is an object backup file, created during the compilationof a .4ge program module.

file.pbr is a FORM4GL source backup file.

file.fbm is a FORM4GL object backup file.

Under normal conditions, INFORMIX-4GL creates the backup files andintermediate files as necessary and deletes them upon a successful compila-tion. If you interrupt a compilation, you may find one or more of these filesin your current directory.

During the compilation process, INFORMIX-4GL stores a backup copy of thefile.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 systemcrash, you may need to replace the modified file.4gl file with the backup copycontained 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 thesame directory. After an editing session terminates abnormally, for example,you must delete or rename any backup file before you can resume editingyour 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 RapidDevelopment System. Except as otherwise noted, the other chapters andappendixes of this manual describe features that are identical in both theC Compiler Version and Rapid Development System Version implementa-tions of INFORMIX-4GL.

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

1-36 Compiling 4GL Source Files

Page 61: Manual Informix

The INFORMIX-4GL Menu

The INFORMIX-4GL MenuThe r4gl command briefly displays the INFORMIX-4GL banner and sign-onmessage. Then a menu appears, called the INFORMIX-4GL Menu:

INFORMIX-4GL: Module Form Program Query-language ExitCreate, 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 theProgrammer’s Environment. You have five options:

Module Work on an INFORMIX-4GL program module.

Form Work on a screen form.

Program Specify components of a multi-module program.

Query-language Use the SQL interactive interface, if you have INFOR-MIX-SQL installed on your system.

Exit Return to the operating system.

The first three options display new menus that are described in the pages thatfollow. (You can also press CTRL-W at any menu to display an on-line helpmessage that describes your options.) As at any 4GL menu, you can select anoption 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 optionthat you choose, and then pressing RETURN.

Compiling 4GL Source Files 1-37

Page 62: Manual Informix

The MODULE Design Menu

The MODULE Design MenuYou can press RETURN or type m or M to select the Module option of theINFORMIX-4GL Menu. This option displays a new menu, called the MODULEDesign Menu. Use this menu to work on an individual 4GL source-code file.

MODULE: Modify New Compile Program_Compile Run Debug ExitChange an existing 4GL program module.

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

The MODULE Design Menu supports the following options:

Modify Change an existing 4GL source-code module.

New Create a new 4GL source-code module.

Compile Compile an existing 4GL source-code module.

Program_Compile Compile a 4GL application program.

Run Execute a compiled 4GL module or multi-moduleapplication program.

Debug Invoke the INFORMIX-4GL Interactive Debuggerto examine an existing 4GL program module orapplication program (if you have the Debuggerproduct installed on your system).

Exit Return to the INFORMIX-4GL Menu.

As in all of the menus of the Programmer’s Environment except the INFOR-MIX-4GL Menu, the Exit option returns control to the higher menu fromwhich you accessed the current menu.

You can use these options to create and compile source-code modules of a4GL application. (See “The FORM Design Menu” later in this chapter forinformation on creating 4GL screen forms. Refer also to “The mkmessageUtility” section of Appendix E for information on creating and compilingprogrammer-defined help messages for an INFORMIX-4GL application.)

1-38 Compiling 4GL Source Files

Page 63: Manual Informix

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 4GLsource-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 theProgrammer’s Environment, INFORMIX-4GL invokes that editor. The 4GLsource file whose filename you specified is the current file.

When you leave the editor, INFORMIX-4GL displays the MODIFY MODULEMenu, with the Compile option highlighted:

MODIFY MODULE: Compile Save-and-exit Discard-and-exitCompile the 4GL module specification.

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

If you press RETURN or type c or C to select the Compile option, INFOR-MIX-4GL displays the COMPILE MODULE Menu:

COMPILE MODULE: Object Runable ExitCreate object file (.4go suffix).

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

The Object option creates a file with a .4go extension. The Runable optioncreates a file with a .4gi extension. Select the Runable option if the currentprogram 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-moduleprogram), then you should use the Object option instead, and you must usethe PROGRAM Design Menu to specify all the component modules.

Compiling 4GL Source Files 1-39

Page 64: Manual Informix

The MODULE Design Menu

After you select Object or Runable, a message near the bottom of the screenwill advise you if INFORMIX-4GL issues a compile-time warning or error. Ifthere are warnings (but no errors), a p-code file is produced. Select the Exitoption of the next menu, and then Save-and-exit at the MODIFY MODULEMenu, if you want to save the p-code file without reading the warnings.

Alternatively, you can examine the warning messages by selecting Correctat the next menu. When you finish editing the .err file that contains thewarnings, 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 ExitCorrect 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 yoursource module with embedded error messages. (You do not need to deleteerror messages, since INFORMIX-4GL does this for you.) Correct your sourcefile, save your changes, and exit from the editor. The MODIFY MODULE Menureappears, prompting you to recompile, or to save or discard your changeswithout compiling.

If there are no compilation errors, the MODIFY MODULE Menu appearswith the Save-and-Exit option highlighted. If you select this option, INFOR-MIX-4GL saves the current source-code module as a disk file with the file-name extension .4gl, and saves the compiled version as a file with the samefilename, but with the extension .4go or .4gi. If you select the Dis-card-and-Exit option, INFORMIX-4GL discards any changes made toyour file since you selected the Modify option.

1-40 Compiling 4GL Source Files

Page 65: Manual Informix

The MODULE Design Menu

The New Option

Select this option to create a new 4GL source-code module.

MODULE: Modify New Compile Program_Compile Run Debug ExitCreate a new 4GL program module.

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

This option resembles the Modify option, but NEW MODULE is the menutitle, 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 withDBEDIT, 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-codemodule without first selecting the Modify option.

MODULE: Modify New Compile Program_Compile Run Debug ExitCompile an existing 4GL program module.

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

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

The Program_Compile Option

The Program_Compile option of the MODULE Design Menu is the sameas the Compile option of the PROGRAM Design Menu (see that option fordetails). It permits you to compile and combine modules as described in the

Compiling 4GL Source Files 1-41

Page 66: Manual Informix

The MODULE Design Menu

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

The Run Option

Select this option to begin execution of a compiled program.

MODULE: Modify New Compile Program_Compile Run Debug ExitExecute an existing 4GL program module or application program.

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

The RUN PROGRAM screen presents a list of compiled modules andprograms, with the highlight on the module corresponding to the current file,if any has been specified. Compiled programs must have the extension .4gito 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 com-piled programs exist, INFORMIX-4GL displays an error message and restoresthe MODULE Design Menu.

The Debug Option

Select this option to use the INFORMIX-4GL Interactive Debugger toanalyze a program. This option is implemented only if you have separatelypurchased and installed the INFORMIX-4GL Interactive Debugger on yoursystem.

MODULE: Modify New Compile Program_Compile Run Debug ExitReturns to the INFORMIX-4GL Menu.

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

1-42 Compiling 4GL Source Files

Page 67: Manual Informix

The FORM Design Menu

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

The Exit Option

Select this option to exit from the MODULE Design Menu and display theINFORMIX-4GL Menu.

MODULE: Modify New Compile Program_Compile Run Debug ExitReturns to the INFORMIX-4GL Menu.

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

The FORM Design MenuYou 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 theFORM Design Menu:

FORM: Modify Generate New Compile ExitChange an existing form specification.

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

You can use this menu to create, modify, and compile screen form specifica-tions. These specifications define visual displays that 4GL applications canuse to query and modify the information in a database. INFORMIX-4GLscreen form specifications are ASCII files that are described in Chapter 4 ofthis manual, and in Chapters 6, 7, and 11 of the INFORMIX-4GL User Guide.

The FORM Design Menu supports the following options:

Modify Change an existing 4GL screen form specification.

Generate Create a default 4GL screen form specification.

Compiling 4GL Source Files 1-43

Page 68: Manual Informix

The FORM Design Menu

New Create a new 4GL screen form specification.

Compile Compile an existing 4GL screen form specification.

Exit Return to the INFORMIX-4GL Menu.

Readers familiar with the menu system of INFORMIX-SQL may noticethat this menu resembles the menu displayed by the Form option of theINFORMIX-SQL Main Menu.

Chapter 4 of this manual and Chapters 6 and 7 of the INFORMIX-4GL UserGuide describe the usage and statement syntax of 4GL screen formspecifications.

The Modify Option

The Modify option of the FORM Design Menu enables you to edit an existingform specification file. It resembles the Modify option in the MODULE DesignMenu, since both options are used to edit program modules.

FORM: Modify Generate New Compile ExitChange an existing form specification.

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

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

1-44 Compiling 4GL Source Files

Page 69: Manual Informix

The FORM Design Menu

If you have not already designated a text editor in this INFORMIX-4GLsession or with DBEDIT, you are prompted for the name of an editor. Then anediting session begins, with the form specification source-code file that youspecified as the current file. When you leave the editor, INFORMIX-4GLdisplays the MODIFY FORM Menu with the Compile option highlighted.

MODIFY FORM: Compile Save-and-exit Discard-and-exitCompile the form specification.

-------------------------------------------------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 ExitCorrect errors in the form specification.

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

Press RETURN to select Correct as your option. An editing session begins ona copy of the current form, with diagnostic error messages embedded wherethe compiler detected errors. INFORMIX-4GL deletes these messages whenyou save and exit from the editor. After you correct the errors, the MODIFYFORM Menu appears again, with the Compile option highlighted. PressRETURN to recompile.

If there are no compilation errors, you are prompted whether to savethe modified form specification file and the compiled form, or to discardthe changes. (Discarding the changes restores the version of your formspecifications from before you chose the Modify option.)

Compiling 4GL Source Files 1-45

Page 70: Manual Informix

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 editlater by selecting the Modify option.

FORM: Modify Generate New Compile ExitGenerate and compile a default form specification.

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

When you select this option, INFORMIX-4GL prompts you to select a data-base, to choose a filename for the form specification, and to identify the tablesthat the form will access. After you provide this information, INFORMIX-4GLcreates and compiles a form specification file. (This is equivalent to runningthe -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 newscreen form specification.

FORM: Modify Generate New Compile ExitCreate a new form specification.

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

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

1-46 Compiling 4GL Source Files

Page 71: Manual Informix

The FORM Design Menu

The Compile Option

The Compile option enables you to compile an existing form specificationfile without going through the Modify option.

FORM: Modify Generate New Compile ExitCompile an existing form specification.

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

INFORMIX-4GL prompts you for the name of the form specification file andthen performs the compilation. If the compilation is not successful, INFOR-MIX-4GL displays the COMPILE FORM Menu with the highlight on the Cor-rect option.

The Exit Option

The Exit option clears the FORM Design Menu from the screen.

FORM: Modify Generate New Compile ExitReturns to the INFORMIX-4GL Menu.

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

Selecting this option restores the INFORMIX-4GL Menu:

INFORMIX-4GL: Module Form Program Query-language ExitCreate, modify or run individual 4GL program modules.

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

Compiling 4GL Source Files 1-47

Page 72: Manual Informix

The PROGRAM Design Menu

The PROGRAM Design MenuAn INFORMIX-4GL program can be a single source-code module thatyou create and compile at the MODULE Design Menu. For applications ofgreater complexity, however, it is often easier to develop and maintain anINFORMIX-4GL program that includes several modules. The INFORMIX-4GLMenu includes the Program option so that you can create multiple-moduleprograms. When you select this option, INFORMIX-4GL searches yourDBPATH directories (see Appendix C) for the program specification data-base, called syspgm4gl. This database describes the runner options and themodules of your program.

If INFORMIX-4GL cannot find this database, you are asked if you want onecreated. If you enter y in response, INFORMIX-4GL creates the syspgm4gldatabase, grants CONNECT privilege to PUBLIC, and displays the PROGRAMDesign Menu. As Database Administrator of syspgm4gl, you can laterrestrict the access of other users.

If syspgm4gl already exists, the PROGRAM Design Menu appears.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitChange 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 programspecification, to compile a program, or to execute or analyze a program.

The PROGRAM Design Menu supports the following eight options:

Modify Change an existing program specification.

New Create a new program specification.

Compile Compile an existing program.

Planned_Compile Display the steps to compile an existing program.

Run Execute an existing program.

Debug Invoke the INFORMIX-4GL Interactive Debugger.

Undefine Delete an existing program specification.

Exit Return to the INFORMIX-4GL Menu.

1-48 Compiling 4GL Source Files

Page 73: Manual Informix

The PROGRAM Design Menu

You must first use the MODULE Design Menu and FORM Design Menuto enter and edit the INFORMIX-4GL statements within the componentsource-code modules of a 4GL program. Then you can use the PROGRAMDesign Menu to identify which modules are part of the same applicationprogram, 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 existing4GL program. (This option is not valid unless at least one program hasalready been specified. If none has, you can create a program specificationby selecting the New option from the same menu.) INFORMIX-4GL promptsyou for the name of the program specification you want to modify. It thendisplays a screen and menu that you can use to update the information in theprogram specification database, as shown in Figure 1-3:

MODIFY PROGRAM: 4GL Globals Other Program_Runner Rename ExitEdit the 4GL sources list.

-------------------------------------------------Press CTRL-W for Help------Program [myprog ]Runner [fglgo ] Runner Path [ ]Debugger [fgldb ] Debugger Path [ ]

4gl Source 4gl Source Path[main ] [/u/john/appl/4GL ][funct ] [/u/john/appl/4GL ][rept ] [/u/john/appl/4GL ][ ] [ ][ ] [ ]

Global Source Global Source Path[ ] [ ][ ] [ ]

Other .4go Other .4go Path[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 nameis myprog. You can change the name by selecting the Rename option. Theprogram name, with extension .4gi, is assigned to the program produced bycompiling and combining all the source files. (Compiling and combining isdone by the Compile option, as described later in this chapter, or by theProgram_Compile option of the MODULE Design Menu.) In this case, therunable program would have the name myprog.4gi.

Compiling 4GL Source Files 1-49

Page 74: Manual Informix

The PROGRAM Design Menu

The 4GL option enables you to update the entries for 4gl Source and 4gl SourcePath. The five rows of fields under these labels form a screen array. If youselect the 4GL option, INFORMIX-4GL executes an INPUT ARRAY statementso you can move through the array and scroll for up to a maximum of 100entries.

The INPUT ARRAY statement description in Chapter 7 explains how to usefunction keys to scroll, delete rows, and insert new rows. (You cannot rede-fine function keys, however, as you can with an INFORMIX-4GL program.)

In the example shown in Figure 1-3, the 4GL source program has beenbroken into three modules: a module containing the MAIN program block(main.4gl), a module containing functions (funct.4gl), and a module contain-ing REPORT statements (rept.4gl). These modules are all located in the direc-tory /u/john/appl/4GL. If a module contains only global variables, you canlist it here or in the Global Source array.

The Globals option enables you to update the Global Source array. If you usethe Global Source array to store a globals module, any modification of the glo-bals module file causes all 4GL modules to be recompiled when you select theCompile option.

The Other option enables you to update the entries for the Other .4go andOther .4go Path fields. This is where you specify the name and location ofother 4GL object files (.4go files) to include in your program. Do not specifythe filename extensions. You can list up to 100 files in this array.

The Program_Runner option enables you to specify the name and locationof the p-code runner to execute your program. You can run INFORMIX-4GLprograms with fglgo (the default) or with a customized p-code runner. A cus-tomized p-code runner is an executable program that you create to run 4GLprograms that call C functions, as described later in this chapter. If you do notmodify the Runner field, your program is executed by fglgo when you selectthe Run option from the PROGRAM Design Menu.

The MODIFY PROGRAM screen form contains two additional fields labeledDebugger and Debugger Path. If you have the INFORMIX-4GL InteractiveDebugger, you can also use the Program_Runner option to enter the nameof a customized Debugger. See the section “RDS Programs That Call C Func-tions” later in this chapter for information about the use of a customizedDebugger. For the procedures to create a customized Debugger, refer toAppendix C of the Guide to the INFORMIX-4GL Interactive Debugger, whichincludes an example.

The Exit option of the MODIFY PROGRAM Menu returns you to thePROGRAM Design Menu.

1-50 Compiling 4GL Source Files

Page 75: Manual Informix

The PROGRAM Design Menu

The New Option

The New option of the PROGRAM Design Menu enables you to create a newspecification of the program modules and libraries that make up the desiredapplication program.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitAdd the compilation definition of a 4GL application program.

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

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

The Compile Option

The Compile option compiles and combines the modules listed in theprogram specification database, taking into account the time when files werelast updated. INFORMIX-4GL compiles only those files that have been modi-fied since they were last compiled, except in the case where you have modi-fied a module listed in the Global Source array. If you have modified a modulethat is listed in the Global Source array, all files are recompiled.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitCompile a 4GL application program.

-------------------------------------------------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

Page 76: Manual Informix

The PROGRAM Design Menu

The Planned_Compile Option

Taking into account the time of last change for the various files in the depen-dency relationships, the Planned_Compile option prompts for a programname and displays a summary of the steps that will be executed if you selectCompile. No compilation actually takes place.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitShow 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

Linking other objects:/u/john/appl/Com/obj.4go

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

The Run Option

Select the Run option to execute a compiled program.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitExecute a 4GL application program

-------------------------------------------------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 optionresembles the Run option of the MODULE Design Menu.

Although .4go files are not displayed, you can also enter the name andextension of a .4go file. Whatever compiled program you select is executedby fglgo, or by the runner that you specified in the Runner field of theProgram Specification screen. This screen was illustrated earlier, in thedescription of the MODIFY PROGRAM Menu.

1-52 Compiling 4GL Source Files

Page 77: Manual Informix

The PROGRAM Design Menu

The Debug Option

The Debug option works like the Run option but enables you to examinea 4GL program with the INFORMIX-4GL Interactive Debugger. This optionis not implemented unless you have purchased the Debugger.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitDrop the compilation definition of a 4GL application program.

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

The Undefine Option

The Undefine option of the PROGRAM Design Menu prompts you for aprogram name and removes the compilation definition of that program fromthe syspgm4gl database. This action removes the definition only. Yourprogram and 4GL modules are not removed.

PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine ExitDrop the compilation definition of a 4GL application program.

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

The Exit Option

The Exit option clears the PROGRAM Design Menu from the screen andrestores the INFORMIX-4GL Menu.

Compiling 4GL Source Files 1-53

Page 78: Manual Informix

The QUERY LANGUAGE Menu

The QUERY LANGUAGE MenuThe SQL interactive interface is identical to the interactive SQL interface ofINFORMIX-SQL. You can use this option only if you have separately pur-chased and installed INFORMIX-SQL on your system.

The Query-language option is placed at the top-level menu so you can testSQL statements without leaving the INFORMIX-4GL Programmer’s Environ-ment. You can also use this option to create, execute, and save SQL scripts.

Creating Executable RDS ProgramsTo create an INFORMIX-4GL application with the INFORMIX-4GL RapidDevelopment 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 fromthe Programmer’s Environment and at the system prompt.

Subsequent sections of this chapter describe how to use the INFORMIX-4GLRapid Development System to compile and execute 4GL programs that callC functions. (These special Rapid Development System procedures requirea C language compiler and linker, which are unnecessary for 4GL applica-tions that do not call programmer-defined C functions.)

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

1-54 Compiling 4GL Source Files

Page 79: Manual Informix

Working in the RDS Programmer’s Environment

Creating a New Source Module

This section outlines the procedure for creating a new module. If your sourcemodule already exists but needs to be modified, skip ahead to the next sec-tion, ‘‘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 Newoption of the MODULE Design Menu. The screen prompts you for a nameto assign to the new module.

• Enter a name for the new module. The name must begin with a letter, andcan include letters, numbers, and underscores. The name must be uniqueamong the files in the same directory, and among the other program mod-ules, if it will be part of a multi-module program. INFORMIX-4GL attachesextension .4gl to this identifier, as the filename of your new sourcemodule.

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 stepsthat 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 currentdirectory and prompts you to select a source file to edit. Use the Arrowkeys to highlight the name of a source module and press RETURN, orenter a filename (with no extension).

If you specified an editor with the DBEDIT environment variable, an editingsession begins automatically. Otherwise, the screen prompts you to specify atext editor.

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

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

Compiling 4GL Source Files 1-55

Page 80: Manual Informix

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 mustbe compiled before it can be executed. After you save your file and exit fromthe 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 selectCompile, the screen prompts you to select among Object, Runable,and Exit options.

What you should do depends on whether your module is a completeprogram, or whether it is one of several .4gl modules that togethercomprise 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 yourprogram module, with the same filename, but with extension .4gi.

• If the module is one module of a multi-module 4GL program, selectObject. This creates a compiled p-code version of your program module,with the same filename, but with extension .4go. See also the proceduresfor combining program modules, which are described later in this section.

If the compiler detects errors after either option, no compiled file iscreated, and the screen prompts you to select Correct or Exit. Follow thefirst two steps on the next page after an error.

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

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

• After the module compiles successfully, the screen prompts you again toCompile, or to Save-and-exit, or to Discard-and-exit. Select the secondoption to save the compiled program. The MODULE Design Menuappears again on your screen.

• If your program requires screen forms, you must select Exit to return to theINFORMIX-4GL Menu and then select Form to display the FORM DesignMenu. See Chapter 4 for information about designing and creating screenforms.

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

1-56 Compiling 4GL Source Files

Page 81: Manual Informix

Working in the RDS Programmer’s Environment

Combining Program Modules

If the module that you compiled is the only module in your program, you arenow ready to run your program, and you can skip the steps that are describedhere. 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 filebefore you can run the program.

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

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

• Enter the name (without a file extension) of the program that you aremodifying, or the name to be assigned to a new program. Names mustbegin with a letter, and can include letters, underscores ( _ ), and numbers.After you enter a valid name, the PROGRAM screen appears, with yourprogram name in the first field.

If you selected Modify, the names and pathnames of the source-codemodules are also displayed. The PROGRAM screen appears below theMODIFY PROGRAM Menu, rather than below the NEW PROGRAM Menu.(Both menus list the same options.)

NEW PROGRAM: 4GL Globals Other Program_Runner Rename ExitEdit the 4GL sources list.

----------------------------------------------- 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

Page 82: Manual Informix

Working in the RDS Programmer’s Environment

• To specify new 4GL modules or edit the list of 4GL modules, pressRETURN to select the 4GL option. You can enter or edit the name of a mod-ule, without the .4gl file extension. Repeat this step for every module. Ifthe module is not in the current directory or in a directory specified by theDBPATH environment variable, enter the pathname to the directorywhere the module resides.

• The name of the runner (and of the Debugger, if you have the INFOR-MIX-4GL Interactive Debugger) are usually as illustrated in thePROGRAM screen, unless your 4GL program calls C functions. A later sec-tion of this chapter, “RDS Programs That Call C Functions,” explains howto create a customized runner or Debugger, which you can then specifyby selecting the Program_Runner option.

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

• If your program includes any .4go modules that you have already com-piled, you can select the Other option to enter or edit their filenames andpathnames.

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

• Select the Compile option of the PROGRAM Design Menu. This producesa file that combines all of your .4gl source files into an executable pro-gram. Its filename is the program name that you specified, with extension.4gi. The screen lists the names of your .4gl source modules and displaysthe 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 producedautomatically when you work at the Programmer’s Environment of theINFORMIX-4GL Rapid Development System.

Executing a Compiled RDS Program

You can type r or press RETURN to select the Run option. This optionexecutes the compiled 4GL program. Menus, screen forms, windows, orother screen output are displayed, according to your program logic and yourkeyboard interaction with the program.

1-58 Compiling 4GL Source Files

Page 83: Manual Informix

Working at the RDS Command Line

Invoking the Debugger

If you are developing or modifying an INFORMIX-4GL program, youhave much greater control over program execution by first invoking theINFORMIX-4GL Interactive Debugger. If you have purchased the Debugger,you can invoke it from the MODULE Design Menu or PROGRAM DesignMenu of the Programmer’s Environment by selecting the Debug option.

See the Guide to the INFORMIX-4GL Interactive Debugger for detailedinformation on the use of the Debugger as a programmer’s productivity tool.

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

Compiling 4GL Source Files 1-59

Page 84: Manual Informix

Working at the RDS Command Line

Figure 1-4 Creating and Running a Single-Module Program

Here the rectangles represent processes controlled by specific commands,and the circles represent files. Arrows indicate whether a file serves as inputor 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 applicationsare 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-codecompiler. (If error messages are produced by the compiler, find them inthe .err file, and edit the .4gl file to correct the errors. Then recompile thecorrected .4gl file.)

TEXTEDITOR

.4glSource

File

P-CODERUNNER

fglgo

P-CODECOMPILER

fglpc

.4goCompiled

p-codeFile

DEBUGGERfgldb

1-60 Compiling 4GL Source Files

Page 85: Manual Informix

Working at the RDS Command Line

• The following command line invokes the p-code runner:

fglgo filenamewhere filename specifies a compiled 4GL file to be executed.

Executing a program that is undergoing development or modification some-times reveals the existence of run-time errors. If you have the INFORMIX-4GLInteractive Debugger, you can invoke it to analyze and identify run-timeerrors in your program by entering the command:

fgldb filename

where filename specifies your compiled 4GL file. You can then recompile andretest the program. When it is ready for use by others, they can use the fglgorunner to execute the compiled program.

A correspondence between commands and menu options of the RDSProgrammer’s Environment is summarized by the following list:

Command Invokes Menu Optionvi UNIX System Editor Module New/Modifyfglpc 4GL P-Code Compiler Compilefglgo 4GL P-Code Runner Runfgldb 4GL Interactive Debugger Debug

Creating or Modifying a 4GL Source File

Use your system editor or another text-editing program to create a .4gl sourcefile, or to modify an existing file. See the documentation of your text editorand the other chapters of this manual for details.

Compiling an RDS Source File

You cannot execute a 4GL program until you have compiled each sourcemodule into a .4go file. Do this at the system prompt by entering the fglpccommand, which compiles your 4GL source code, and generates a file con-taining tables of information and blocks of p-code. You can then run thiscompiled code by using the INFORMIX-4GL p-code runner (or the INFOR-MIX-4GL Interactive Debugger, if you have the Debugger).

The INFORMIX-4GL source-code module to be compiled should have the fileextension .4gl. The syntax of a fglpc command line follows:

Syntax

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

Compiling 4GL Source Files 1-61

Page 86: Manual Informix

Working at the RDS Command Line

Explanation

-V displays the version number of the software.

-ansi instructs the compiler to check all SQL statements forcompliance with ANSI standards.

-a causes your compiled program to check array bounds at runtime.

-p pathname stores object (.4go) files and error (.err) files in the directoryspecified by pathname.

source.4gl is the name of an INFORMIX-4GL source-code module.

Notes

1. The fglpc command reads source.4gl files and creates a compiled versionof each, with the filename source.4go. You can specify any number ofsource files, in any order, with or without their .4gl filename extensions.

2. If you specify the -V option, the screen displays the version number ofyour SQL and p-code compiler software. Any other command options areignored. After displaying this information, the program terminates with-out compiling.

3. If you specify the -ansi option, it must appear first in your list of fglpccommand arguments. The -ansi option asks for compile-time warningmessages if your source code includes Informix extensions to the ANSIstandard for SQL. (Chapter 7 lists the Informix syntax extensions.)

4. If an error or warning occurs during compilation, INFORMIX-4GL createsa file called source.err. Look in source.err to find where the error or warn-ing occurred in your code.

5. You can use the -p pathname option to specify a non-default directory forthe .4go and .err files. Otherwise, any files produced by fglpc are storedin your current working directory.

6. Since the -a option requires additional processing, you may want to usethis option only for debugging during development.

Examples

The following command compiles a 4GL source file single.4gl, and creates afile 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

Page 87: Manual Informix

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 aresaved 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 concat-enated into a single file, as represented in Figure 1-5:

Figure 1-5 Creating and Running a Multi-Module Program

TEXTEDITOR

.4glSourceFiles

CONCATENATIONUTILITY

P-CODECOMPILER

fglpc

.4gop-codeObjectFiles

.4gip-code

ExecutableFiles

P-CODERUNNER

fglgo

Compiling 4GL Source Files 1-63

Page 88: Manual Informix

Working at the RDS Command Line

The UNIX cat command combines the listed files into the file specified afterthe 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 exten-sion. Throughout this manual, extension .4gi designates runable files that have beencompiled (and concatenated, if several source modules comprise the program). Youmay wish to follow this convention in naming files, since only .4gi files are displayedfrom within the Programmer’s Environment. This convention is also a convenientway to distinguish complete program files from object files that are individual mod-ules of a multi-module program.

If your 4GL program calls C functions or INFORMIX-ESQL/C functions, you mustfollow procedures that are described in the section ‘‘RDS Programs That Call C Func-tions’’ before you can run your application.

Running RDS Programs

To execute a compiled 4GL program from the command line, you can invokethe 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 versionnumber. After displaying this information, the programquits without invoking the p-code runner.

-a causes array bounds checking at run time.

filename is the name of a compiled 4GL file. The filename must havea .4go or .4gi extension. You do not need to enter this exten-sion on the command line.

args are any arguments required by your 4GL program.

1-64 Compiling 4GL Source Files

Page 89: Manual Informix

Working at the RDS Command Line

Notes

1. If you do not specify a filename extension in the command line, fglgolooks first for the filename with a .4gi extension, and then for the filenamewith a .4go extension.

2. To run a 4GL program that calls programmer-defined C functions, youcannot use fglgo. You must instead use a customized p-code runner. Thesection ‘‘RDS Programs That Call C Functions’’ describes how to create acustomized runner.

Examples

To run a compiled program named myprog.4go, enter the following com-mand 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 moduleand then combine them by an operating system concatenation utility, asdescribed in an earlier section. For example, if mod1.4go, mod2.4go, andmod3.4go are compiled INFORMIX-4GL modules that you want to run as oneprogram, 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 Interac-tive Debugger. This 4GL source-code debugger is a p-code runner with a richcommand set for analyzing 4GL programs. You can use the Debugger tolocate logical and run-time errors in your 4GL programs and to become morefamiliar with 4GL programs. The Debugger must be purchased separatelyfrom INFORMIX-4GL.

Compiling 4GL Source Files 1-65

Page 90: Manual Informix

Working at the RDS Command Line

If you have the Debugger, you can invoke it at the system prompt by a com-mand line of the form:

fgldb filename

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

RDS Programs That Call C Functions

If your INFORMIX-4GL Rapid Development System program calls program-mer-defined C functions, you must create a customized runner to execute theprogram. You can do this by following two steps:

1. Edit a structure definition file to contain information about your C func-tions. 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 func-tions. To do this, use the cfglgo command.

You can then use the runner produced by the cfglgo command to run the4GL program that calls your C functions. Both the fgiusr.c file and thecfglgo command are described in the pages that follow.

Note: To create a customized runner, you must have a C compiler installedon your system. You do not need a C compiler, however, and you do not needto follow the procedures described in this section, if the only functions that yourINFORMIX-4GL Rapid Development System program calls are INFORMIX-4GLor INFORMIX-ESQL/C library functions, or functions written in the INFOR-MIX-4GL language.

1-66 Compiling 4GL Source Files

Page 91: Manual Informix

Working at the RDS Command Line

Editing the fgiusr.c File

With your INFORMIX-4GL software, you receive a file named fgiusr.c. Thisfile is located in the etc subdirectory of the directory in which you installINFORMIX-4GL (that is, in INFORMIXDIR/etc). The following listing showsthe 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 numberof programmer-defined C functions.

Compiling 4GL Source Files 1-67

Page 92: Manual Informix

Working at the RDS Command Line

To edit fgiusr.c, you can copy the file to any directory. (Unless this is yourworking directory at compile time, you must specify the full pathname of theedited 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 doublequotation marks).

The second is a function pointer (the name without quotes).

The third is an integer (for the number of arguments expected by the func-tion). If the number of arguments expected by the function can vary, make thethird argument the maximum number of arguments, prefixed with a minus ( - ) sign.

You must use commas ( , ) to separate the three initializers. Insert a setof initializers for each C function that you declare. A line of three zeroesindicates 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 func-tion-name that has one ( 1 ) argument.

If you have several 4GL programs that call C functions, you can use fgiusr.cin either of two ways:

• You can create one customized p-code runner. In this case, you can editfgiusr.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 allyour 4GL applications.

• You can create several application-specific runners. In this case, you caneither make a copy of the fgiusr.c file (with a new name) for each custom-

1-68 Compiling 4GL Source Files

Page 93: Manual Informix

Working at the RDS Command Line

ized runner, or you can re-edit fgiusr.c to contain information on the Cfunctions for a specific application before you compile and link. If youcreate several runners, you must know which customized runner to usewith each 4GL application.

In some situations the first method is more convenient, since users do nothave 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 canuse cfglgo to compile C modules and INFORMIX-ESQL/C modules that con-tain functions declared in an edited fgiusr.c file.

Syntax

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

Explanation

-V displays the version number of the software.

fgiusr.c is the name of the file that you edited to declare C and/orINFORMIX-ESQL/C functions.

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

-o newfglgo specifies the name of the customized runner.

Notes

1. The cfglgo command compiles and links the edited fgiusr.c file withyour C program files into an executable program that can run your 4GLapplication.

2. You can rename an edited structure definition file. If you do so, specify itsnew filename in place of fgiusr.c.

3. If you do not specify the -o newfglgo option, the new runner is given thedefault name a.out.

4. You can specify any number of uncompiled or compiled C or INFOR-MIX-ESQL/C files in a cfglgo command line.

5. You must have the INFORMIX-ESQL/C product to compile INFOR-MIX-ESQL/C files with cfglgo.

Compiling 4GL Source Files 1-69

Page 94: Manual Informix

Working at the RDS Command Line

6. If the fgiusr.c file to be linked is not in the current directory, you mustspecify a full pathname.

7. The customized runner can also run 4GL programs that do not call Cfunctions.

8. The -V option displays the release version numbers of your p-code andSQL software and returns the system prompt. All other arguments areignored, 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

Page 95: Manual Informix

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"23 int prdate();4 cfunc_t usrcfuncs[] =5 {6 "prdate", prdate, 0,7 0, 0, 08 };

An explanation of this example of an fgiusr.c file follows:

line 1: The file ‘‘fgicfunc.h’’ is always included. This line already existsin the unedited fgiusr.c file.

line 3: This is the declaration of the function prdate( ). You must addthis line to the file.

line 4: This line already exists in the unedited file. It declares thestructure array usrcfuncs.

line 6: This line contains the initializers for function prdate( ). Sinceit expects no arguments, the third value is zero.

line 7: The line of three zeros indicates that no more functions are tobe included.

In this example, you can use the following commands to compile the 4GLprogram, 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

Page 96: Manual Informix

RDS Program Filename Extensions

Running Programs That Call C Functions

After you create a customized runner, you can use it to execute any 4GLprogram 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 thesyntax 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 callsC functions. See Appendix C of the Guide to the INFORMIX-4GL InteractiveDebugger for details and an example of how to create a customized Debugger.

You cannot create a customized runner or a customized Debugger from themenus and screen forms of the Programmer’s Environment. You must exit tothe system prompt and follow the procedures that were just described if youare developing a 4GL program that calls user-defined C functions. Then youcan return to the Programmer’s Environment and use the Program_Runneroption of the MODIFY PROGRAM Menu or NEW PROGRAM Menu to specifythe name of a customized runner or Debugger.

RDS Program Filename ExtensionsSource, runable, error, and backup files generated by INFORMIX-4GL arestored in the current directory and are labeled with a filename extension. Thefollowing list shows the file extensions for the source, runable, and error files.These files are produced during the normal course of using the INFOR-MIX-4GL Rapid Development System.

file.4gl is an INFORMIX-4GL source file.

file.4go is an INFORMIX-4GL file that has been compiled to p-code.

file.4gi is an INFORMIX-4GL file that has been compiled to p-code.

file.err is an INFORMIX-4GL source error file, created when an attempt tocompile a module fails or produces a warning. The file containsthe 4GL source code plus compiler syntax warnings or errormessages.

file.erc is an INFORMIX-4GL object error file, created when an attempt tocompile or to link a non-INFORMIX-4GL source-code or objectmodule fails. The file contains 4GL source code and annotatedcompiler errors.

form.per is a FORM4GL source file.

form.frm is a FORM4GL object file.

form.err is a FORM4GL source error file.

1-72 Compiling 4GL Source Files

Page 97: Manual Informix

RDS Program Filename Extensions

The last three files do not exist unless you create or modify a screen formspecification file, as described in Chapter 4.

The next page lists the corresponding file extensions for the backup files thatINFORMIX-4GL automatically creates when you use the Programmer’s Envi-ronment to process 4GL source files.

The following list identifies backup files that are produced when you useINFORMIX-4GL from the Programmer’s Environment.

file.4bl is an INFORMIX-4GL source backup file, created during the mod-ification and compilation of a .4gl program module.

file.4bo is an object backup file, created during the compilation of a .4goprogram module.

file.4be is an object backup file, created during the compilation of a .4giprogram module.

file.pbr is a FORM4GL source backup file.file.fbm is a FORM4GL object backup file.

Under normal conditions, INFORMIX-4GL creates the backup files and inter-mediate files as necessary, and deletes them upon a successful compilation. Ifyou interrupt a compilation, you may find one or more of the files in yourcurrent directory.

If you compile with a fglpc command line that includes the p pathnameoption, INFORMIX-4GL creates the .4gi, .4go, .err, and corresponding backupfiles in the directory specified by pathname, rather than in your currentdirectory.

During the compilation process, INFORMIX-4GL stores a backup copy of thefile.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 systemcrash, you may need to replace the modified file.4gl file with the backup copycontained 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 thesame directory. After an editing session terminates abnormally, for example,you must delete or rename any backup file before you can resume editingyour 4GL module or form from the Programmer’s Environment.

This concludes the description of the Rapid Development System. Except asotherwise noted, the descriptions of INFORMIX-4GL elsewhere in this man-ual describe features that are identical in both the C Compiler Version andRapid Development System implementations of INFORMIX-4GL.

Compiling 4GL Source Files 1-73

Page 98: Manual Informix

RDS Program Filename Extensions

1-74 Compiling 4GL Source Files

Page 99: Manual Informix

Chapter

2

INFORMIX-4GLProgrammingChapter Overview 3

Language Conventions 3Comments 3INFORMIX-4GL Identifiers 4Scope of Identifiers 4Constants 5

String Constants 5Integer Constants 5Floating Number Constants 5Date and Time Constants 6

Program Variables 6Data Types 7

SMALLINT 7INTEGER 7DECIMAL [ (m [, n ] ) ] 7SMALLFLOAT 8FLOAT [ ( n ) ] 8MONEY [ ( m [ , n ] ) ] 8CHAR [ ( n ) ] 8DATE 9DATETIME 9INTERVAL 9LIKE table.column 9RECORD 9ARRAY [i, j, k] OF type 10

Data Conversion 10

Page 100: Manual Informix

Operators and Expressions 11Number Expressions 11String Expressions 12Date and Time Expressions 12Boolean Expressions 13Expressions in INFORMIX-4GL Statements 13

Binding to Database and Forms 14The THRU Keyword and the .* Notation 15

INFORMIX-4GL Statements 16Variable Definition 17Assignment 17Program Organization 17Program Flow 18Screen Interaction 19Report Generation 21Error and Exception Handling 21

Error Handling 22Exception Handling 23

Data Validation 23

Built-in Functions 24ASCII 25CLIPPED 27COLUMN 29CURRENT 30DATE 32DATE( ) 33DAY( ) 34EXTEND( ) 35LENGTH( ) 38MDY( ) 39MONTH( ) 40TIME 41TODAY 42UNITS 43USING 44

Formatting Number Expressions 44Formatting DATE Expressions 46

WEEKDAY( ) 53YEAR( ) 54

C Functions 55

2-2 INFORMIX-4GL Programming

Page 101: Manual Informix

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

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

CommentsFor clarity and to simplify program maintenance, it is recommended that youdocument your code by including comments in your 4GL source files. Youcan also use comment symbols during program development to disablestatements without deleting them. You can indicate comments in any of threeways:

• 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 commentterminates at the end of the line.

INFORMIX-4GL Programming 2-3

Page 102: Manual Informix

INFORMIX-4GL Identifiers

• You can also use a pair of hyphens or minus signs (-- ) to begin a com-ment that terminates at the end of the line. (Use of this comment indicatorconforms to the ANSI standard.)

All text between the braces (or from the # or -- indicator to the end of theline) is ignored.

INFORMIX-4GL IdentifiersINFORMIX-4GL programs can reference constants, local, module, and globalprogram variables, screen forms, labels, windows, functions, and reports.With the exception of constants, each of these must have an INFORMIX-4GLidentifier as a name. An identifier is a sequence of letters, digits, and under-scores ( _ ). The first character must be a letter or an underscore. Only the firsteight characters are significant, and the case of letters is ignored. Identifiersmust not be the same as keywords (which are listed in Appendix D).

INFORMIX-4GL identifiers can be the same as SQL identifiers, but such userequires special attention when you use the identifier in an SQL statement.(See Chapter 3 for a discussion of SQL statements, objects, cursors, andidentifiers.)

Scope of IdentifiersProgram variables can be either local, modular, or global in their scope ofreference.

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

• Module variables must be defined before the first program block (that is,before the MAIN statement or before any REPORT or FUNCTION state-ment). 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 fol-lowed by an END GLOBALS statement) or in a separate globals file. Otherprogram files using these variables must include the statement GLOBALS‘‘globals-filename’’ (where globals-filename contains the definitions of theglobal variables).

2-4 INFORMIX-4GL Programming

Page 103: Manual Informix

Constants

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

Constants4GL 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 tovariables and to database columns. NULL values are distinct from blankstrings or zeros for number variables and columns, and represent unknownvalues. See the section “NULL Values” in Chapter 3 for details about thebehavior of NULL values in expressions.

String Constants

String constants are sequences of up to 80 characters enclosed within doublequotes. The constant must be written on a single line (no embedded newlines). You can create longer string variables by concatenating string con-stants. To include a double quote in a string, precede the double quote withthe 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 embeddedcommas and without a decimal point. You can precede the integer with aminus or plus sign, but there can be no space, tab, or new line between thesign and the first digit:

15 -12 13938

Floating Number Constants

Non-integer number constants are expressed only in base 10 with a decimalpoint. You can use exponential notation as well:

123.456 = 1.23456e2 = 123456.0e-3

INFORMIX-4GL Programming 2-5

Page 104: Manual Informix

Program Variables

Date and Time Constants

String constants that evaluate to DATE values must be enclosed within dou-ble quotation marks and can be expressed either with the format mm/dd/yy orwith 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 themaximum for that month). Both yy and yyyy stand for the year. When you useonly two digits for the year, INFORMIX-4GL assumes that you intend to entera year beginning with the digits ‘‘19.’’

Values of data types DATETIME or INTERVAL can appear as constants withindouble 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 calen-dar date values and/or time-of-day values for DATETIME, or else date or timevalues for INTERVAL; and qualifier identifies the largest and smallest unitsthat the values describe. The following example specifies an instant in time onMarch 6th, 1989, and illustrates the delimiters that separate fields within thevalues:

DATETIME (89-3-6 09:55:30.825) YEAR TO FRACTION(3)

You can prefix an INTERVAL literal with ‘‘+’’ or ‘‘-’’ to indicate a positive ornegative interval. If the qualifier is only a single field, an INTERVAL can alsobe 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 desig-nates n decimal-place fractions of a second, for 1 ≤ n ≤ 5.) For example, thismeans ‘‘six months’’:

6 UNITS MONTH

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

Program VariablesInformation transfer among a 4GL screen, report, and database occursthrough named memory locations called program variables. You mustdefine the data storage required by a program variable before you can

2-6 INFORMIX-4GL Programming

Page 105: Manual Informix

Data Types

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

Data TypesINFORMIX-4GL variables must have one of the following data types:

SMALLINT MONEY [ (m [ , n ] ) ]

INTEGER CHAR [ ( n ) ]INT CHARACTER [ (n ) ]

DECIMAL [ (m [ , n ] ) ] DATEDEC [ ( m [ , n ] ) ]NUMERIC [ (m [ , n ] ) ] DATETIME qualifier

SMALLFLOAT INTERVAL qualifierREALRECORD [ LIKE table. * ]FLOAT [ ( n ) ]DOUBLE PRECISION [ ( n ) ] 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 ofm (≤ 32) significant digits (the precision) and n (≤ m) digits to the right of thedecimal point (the scale). When you give values for both m and n, the decimalvariable obeys fixed-point arithmetic. All numbers with an absolute valueless than 0.5 × 10-n have the value zero. The largest absolute value of avariable 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 thevariable 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 for-matting instructions, DECIMAL(m) variables have two decimal places to the

INFORMIX-4GL Programming 2-7

Page 106: Manual Informix

Data Types

right of the decimal point (and an exponent, if necessary). If you designate norange or precision parameters, the default is DECIMAL(16), a floatingdecimal.

You can also use the keywords DEC or NUMERIC as synonyms for DECIMAL.

SMALLFLOAT

This data type includes binary floating-point numbers corresponding to thefloat 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 thedouble C data type. Here (n) , a whole number between 1 and 14, is anoptional parameter to specify the precision. INFORMIX-4GL does not use thisparameter, 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 param-eters. The range of values for columns of type MONEY(m, n) is the same as forcolumns of type DECIMAL(m, n), but variables of type MONEY are displayedwith a currency symbol (by default, the dollar sign). The type MONEY(m) isdefined as DECIMAL(m, 2) and, if no parameter is given, MONEY is taken tobe DECIMAL(16, 2). Regardless of the number of parameters, INFORMIX-4GLalways 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 thekeyword CHAR and do not specify a length, INFORMIX-4GL interprets this tomean CHAR(1). You can refer to substrings of CHAR type program variablesin LET, ERROR, MESSAGE, and PROMPT statements with the notation char-variable[m,n], which selects the mth through the nth components of the vari-able char-variable. (The square brackets are literal, not symbols to indicate anoption.)

You can use the keyword CHARACTER as a synonym for CHAR.

2-8 INFORMIX-4GL Programming

Page 107: Manual Informix

Data Types

DATE

These are dates from a DATE column or expression, or entered as a characterstring in one of the formats described earlier in the DATE subsection of ‘‘Dateand 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-dayspecifications. A DATETIME value specifies a contiguous sequence of thefields: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, and FRACTION (of asecond). A value is entered as a character string, in one of the formatsdescribed earlier in the section ‘‘Date and Time Constants.’’ Values are storedinternally as decimal numbers with a scale of zero, with a precision factorcorresponding 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 moreof the same units as DATETIME. A value is entered as a character string inone of the formats described earlier in the section ‘‘Date and TimeConstants.’’ INTERVAL values specify a contiguous sequence from oneof 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 fora field. Internal storage is the same as for DATETIME values. See alsoAppendix J, “Working with DATETIME and INTERVAL Data.”

LIKE table.column

You can define the data type of a variable indirectly by indicating that itshould have the same data type as a column in the database. If the columnhas type SERIAL, INFORMIX-4GL assigns it the data type INTEGER butenforces none of the other restrictions on SERIAL types. (Chapter 3 containsthe definition of the SERIAL data type.)

RECORD

This data type describes a set of variables of possibly differing datatypes, including other records. You can refer to individual elements asrecord_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 limita-tions on using record-name.*.) You can define a record by listing its elements

INFORMIX-4GL Programming 2-9

Page 108: Manual Informix

Data Conversion

and their types, or by defining it to be LIKE table.* , where table is a table in thedatabase. If defined LIKE table.*, the elements of the record have the samenames 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. ARRAYvariables can have from one to three dimensions. You can have arrays ofrecords, but not arrays of arrays. Here the square brackets ( [ ] ) are requiredand 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 char-array[i,j,k][m,n] notation. In this example, i,j,k are indexes into the array, m isthe starting position of the substring, and n is the stopping position ofthe substring.

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

Data ConversionINFORMIX-4GL performs data-type conversion without objection when theprocess 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 stringrepresentation of a number or a date in an arithmetic expression, INFOR-MIX-4GL converts the string or date to an appropriate number. INFOR-MIX-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 anaddition, but adding the string ‘‘John’’ to a number produces an error.

INFORMIX-4GL carries out all arithmetic in an arithmetic expression in typeDECIMAL. The type of the resulting variable determines the format of thestored or printed result. The following rules apply to the precision and scaleof the DECIMAL variable that results from an arithmetic operation on twonumbers:

• All operands, if not already DECIMAL, are converted to DECIMAL, and theresulting number is DECIMAL.

Convert Type ToFLOAT DECIMAL(16)SMALLFLOAT DECIMAL(8)INTEGER DECIMAL(10,0)SMALLINT DECIMAL(5,0)

• The precision and scale of the result of an arithmetic operation depend onthe precision and scale of the operands and on the type of arithmetic

2-10 INFORMIX-4GL Programming

Page 109: Manual Informix

Operators and Expressions

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

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

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

• Leading or trailing zeros are not considered significant digits, and do notcontribute to the determination of precision and scale.

In this table, p1 and s1 are the precision and scale of the first operand, and p2and s2 are the precision and scale of the second operand.

Operation Precision and Scale of ResultAddition and Precision: MIN(32, MAX(p1 - s1, p2 - s2) + MAX(s1, s2) + 1)Subtraction Scale: MAX(s1, s2)

Multiplication Precision: MIN(32, p1+ p2)Scale: s1 +s2

Division Precision: 32Scale: 32 - p1 + s1 - s2 (This cannot be negative.)

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

Number Expressions

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

INFORMIX-4GL Programming 2-11

Page 110: Manual Informix

Operators and Expressions

Operator Operation** Exponentiation

* Multiplication/ Divisionmod Modulus

+ Addition- Subtraction

String variables that are character representations of numbers are convertedto numbers when used in number expressions. A string that is not a characterrepresentation 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 afunction returning a CHAR type; or any combination of these, combined oraltered by the following string operators:

Operator Operation, Concatenation[m,n] Substring where m is the starting position

and n is the ending positionCLIPPED Drop trailing blanksUSING FormattingWORDWRAP Display long strings in multiple lines

Number constants, variables, and columns are converted to their characterrepresentation when used in string expressions. See the description of theUSING function near the end of this chapter for information about format-ting numbers and dates. The WORDWRAP function is used only in 4GLreports, and is described in Chapter 5. The next page lists 4GL Boolean oper-ators on string expressions.

Date and Time Expressions

Date and time expressions are constants, variables, column names, stringliterals, or expressions with the UNITS, TODAY, or CURRENT keywords thatevaluate to a DATE, DATETIME, or INTERVAL value. They can also be anydate or time expression combined with another date or time expression(or with a number) by an arithmetic operator, as summarized in the “Opera-tions on DATETIME and INTERVAL Values” section of Appendix J.

Some arithmetic operations involving date and time values require that youuse the EXTEND function to adjust the precision of the date or time value. Youcan read more about EXTEND later in this chapter.

2-12 INFORMIX-4GL Programming

Page 111: Manual Informix

Operators and Expressions

Boolean Expressions

A Boolean expression evaluates to TRUE or FALSE (or UNKNOWN, if NULL valuesare 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 Operation= Equal to!= or <> 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 collatingorder, as listed in Appendix H. Lowercase letters are after uppercaseletters, 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 [ ESCAPE " esc-char " ]

• 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 )

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 foran 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 anynon-zero number and FALSE is zero. In these statements you can use anumber expression where a Boolean expression is called for. You can use aBoolean expression where a number expression would be expected, yielding1 or 0. You can use a string expression that is a representation of a number

INFORMIX-4GL Programming 2-13

Page 112: Manual Informix

Binding to Database and Forms

anywhere that a number expression is allowed. If you use a string expressionwhere a Boolean expression is expected and the string expression does notrepresent a number, it will be evaluated as zero or FALSE.

A Boolean expression containing a NULL value has an UNKNOWN truthvalue, but it is treated as FALSE in INFORMIX-4GL statements. This can leadto unfamiliar consequences. If a is a Boolean expression, the compoundexpression 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), itstruth value is UNKNOWN. The truth value of NOT a is also UNKNOWN.INFORMIX-4GL treats both these and their combination with OR as FALSE. Ifthere is any chance that a variable may have a NULL value, you should test itbefore using it in a Boolean expression. See the section “NULL Values” inChapter 3 for more details.

Binding to Database and FormsRegardless of how you have defined them, there is no implicit relationshipbetween program variables, screen fields, and database columns. Even whena variable lname is defined to be LIKE customer.lname, changes to the pro-gram variable do not imply any change in the column value. Similarly, evenif you created screen field customer.lname using the same database columnas a model, there is no inherent connection between the program variable andthe field. You must indicate the binding explicitly in any 4GL statement thatconnects program variables to screen forms or to database columns.

The following two statements take input from the screen and insert the valueentered on the screen into the database. Here the @ sign tells INFORMIX-4GLthat the first lname is the name of a database column.

INPUT lname FROM customer.lnameINSERT INTO customer (@lname) VALUES (lname)

Some statements permit temporary binding through the identity of the vari-able name and the screen field name. (See the individual statement descrip-tions in Chapter 7 for the appropriate syntax.) The following statement couldreplace the previous INPUT statement:

INPUT BY NAME lname

2-14 INFORMIX-4GL Programming

Page 113: Manual Informix

The THRU Keyword and the .* Notation

The THRU Keyword and the .* NotationINFORMIX-4GL provides two devices to simplify the writing of 4GL state-ments that refer to elements of a record or columns of a table. One of thesedevices involves the keyword THRU (or THROUGH, its synonym), and theother involves the .* notation.

INITIALIZE pr_rec.element4THRU pr_rec.element8 TO NULL

DISPLAY pr_rec.* TO sc_rec.*

The INITIALIZE statement above sets to NULL the values of program vari-ables 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 onthe screen fields described by the screen record sc_rec. (Chapter 4 describesscreen records.)

With one exception, discussed at the end of this section, these devicesare a shorthand for writing out a partial or full list of record elements or thecolumns of a table, with comma ( , ) separating individual items. The orderof 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 isno shorthand for a partial listing of columns of a table.

• In the definition of a screen record, THRU runs through all the fields in theorder that they are listed in the ATTRIBUTES section of the form specifica-tion 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;...INSTRUCTIONSSCREEN RECORD sc_rec (tab1.cc THRU tab3.bb)

INFORMIX-4GL Programming 2-15

Page 114: Manual Informix

INFORMIX-4GL Statements

The previous excerpt from a form specification file leads to the followinglist of elements of sc_rec:

tab1.cctab2.aatab2.bbtab3.aatab3.bb

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

• You cannot use either THRU or the .* notation on a record that contains anarray among its elements. For example, you cannot use myrec.* to referto all the elements of a record defined as follows:

DEFINE myrec RECORDri INTEGER,ra ARRAY[2] OF INTEGEREND RECORD

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

• You cannot use THRU or the .* notation in the argument list when defininga function or report program block. You can, however, list a record as anargument of a function or of a report.

The exception to .* expanding to a list occurs when you use it in a 4GLUPDATE statement. The notation

UPDATE table1 SET table1.* = pr_rec.*

is expanded by INFORMIX-4GL to the proper syntax

UPDATE table1SET table1.col1 = pr_rec.element1,

table1.col2 = pr_rec.element2,...

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

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

2-16 INFORMIX-4GL Programming

Page 115: Manual Informix

Variable Definition

Variable DefinitionYou 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 aprogram block (to define local variables) or must be withina GLOBALS statement (to define global variables). Variablesdefined after the GLOBALS section (if it is present) and beforeMAIN, the first FUNCTION, or first REPORT section of aprogram module have modular scope.

AssignmentYou can assign values directly to program variables with one of twostatements:

LET assigns the value of an expression to a simple programvariable or to a component of an array or a record. Youcannot use a single LET statement to assign values to anentire record or an array.

INITIALIZE 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 databasethat are not DATETIME or INTERVAL. You can then use theINITIALIZE statement to assign these default values tosimple or record variables.

Program OrganizationINFORMIX-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 mustoccur once, and only once, in every INFORMIX-4GL pro-gram. INFORMIX-4GL passes program control initially to theMAIN program block when you execute your program. Thelast statement in the MAIN program block must be the ENDMAIN statement. After INFORMIX-4GL executes the ENDMAIN statement, it terminates the program.

FUNCTION contains a sequence of INFORMIX-4GL statements that per-form a desired task and terminates with the END FUNCTIONstatement. A function can return zero or more values to the

INFORMIX-4GL Programming 2-17

Page 116: Manual Informix

Program Flow

routine that called it. You can pass the values of variables tofunctions as parameters.

REPORT contains format and output specifications for a report.

GLOBALS identifies those program variables that have a global scopeof reference.

A program must contain only one MAIN statement, and can have at most oneGLOBALS statement that includes DEFINE statements. No restrictions applyto the number of FUNCTION or REPORT program blocks that can appear in aprogram or in a module. (A module is a system file that contains one or moreprogram segments.) You can place all program blocks in a single module, orput each function in a separate module, or use any combination in between.

A GLOBALS statement containing DEFINE statements must either be ina module by itself or be the first statement (or the second if a DATABASEstatement also appears in the module) in the module containing the MAINprogram block. Any module containing routines that refer to global variablesmust begin with a GLOBALS statement giving the pathname of the modulethat defines the global variables. (See the GLOBALS statement in Chapter 7for full details.)

Modules can be compiled separately and linked later, permitting you tocreate a library of INFORMIX-4GL functions and to call them from differentmodules. In addition, your program can call C functions. See the section “CFunctions,” later in this chapter, for the rules governing C functions called byINFORMIX-4GL programs.

Program FlowINFORMIX-4GL has many statements that control the flow of a program.These statements are included in INFORMIX-4GL because they simplifythe 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 withinan expression.

FOR begins an indexed loop of statements (ended by END FOR)that will be executed until the index reaches a programmer-supplied value.

FOREACH begins a loop of statements (ended by END FOREACH) thatwill be executed for each row that is returned by a query ofthe database.

2-18 INFORMIX-4GL Programming

Page 117: Manual Informix

Screen Interaction

WHILE begins a loop of statements (ended by END WHILE) thatwill be executed until a programmer-supplied Booleanexpression becomes false.

CONTINUE permits a premature cycling of a loop or menu.

EXIT permits a premature exit from a FOR, FOREACH, WHILE,MENU, INPUT, or CASE statement, or from the entireprogram.

IF executes one or more statements conditionally (ended byEND IF).

CASE executes a different sequence of statements (ended by ENDCASE) depending upon the current value of an expression.

GOTO passes program control immediately to a designated place inthe program.

LABEL marks the place in the program where a GOTO statement canpass control.

SLEEP causes the program to pause for a specified length of time.

RUN executes an operating system program and returns controlto the INFORMIX-4GL program.

Screen InteractionThe next 18 statements allow the program to interact with the screen. The firststatement constructs a menu; the next five statements provide control overclearing the screen, printing messages, retrieving user input, and setting updefault values for screen parameters, special keys, and help files. The nextthree statements are window management statements. The last nine state-ments 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 menuoption.

CLEAR optionally clears specific screen fields, all screen fields, theentire screen, or a window.

ERROR prints a message in reverse video on the Error line and ringsthe terminal bell.

MESSAGE prints a message on the Message line.

PROMPT prints a message on the Prompt line and returns the user’sresponse.

INFORMIX-4GL Programming 2-19

Page 118: Manual Informix

Screen Interaction

OPTIONS specifies the Message, Prompt, Form, and Comment linesrelative to the screen or current window, as well as any keyand help file designations. You can also specify a new Errorline with the OPTIONS statement, but the error line remainsrelative to the screen.

OPENWINDOW

creates a window, with or without a border, at a given loca-tion and makes it available for use. You can explicitly specifythe size of the window or let INFORMIX-4GL determine thesize of the window from a given screen form.

CURRENTWINDOW

specifies the current or ‘‘topmost’’ window. All input andoutput is done in the current window.

CLOSEWINDOW

closes the window that you specify, restoring the ‘‘topmost’’window (of those that remain) as the current window.

OPEN FORM opens the compiled screen form and associates an INFOR-MIX-4GL identifier with the form.

DISPLAYFORM

displays the named form on the screen or in a window,displacing whatever was on the screen or window below theForm line.

CLOSE FORM closes the file containing the named screen form and releasesits association with the INFORMIX-4GL identifier.

CONSTRUCT takes user input from a screen form and creates a characterstring that can be used as the WHERE clause of a SELECTstatement. This is the INFORMIX-4GL mechanism forperforming a query-by-example.

DISPLAY displays expressions and variables in fields of a screen form,at a specific position on the screen, in a window, or on thenext line.

DISPLAYARRAY

displays a program array to a screen array and allowsscrolling through the array.

INPUT takes user-entered data from a screen form and puts the datainto program variables. You can specify sequences of state-ments to be executed during the INPUT statement before orafter the cursor enters any field or after the user indicatesthat entry is complete. You can also trap function or controlkeys and specify an appropriate sequence of statements.

INPUTARRAY

is an extension of the INPUT statement that takes dataentered by a user into a screen array and puts the informa-tion into an array of program variables. The user can scrollthrough the array, insert new rows into the array, and deleterows from the array by using function keys.

2-20 INFORMIX-4GL Programming

Page 119: Manual Informix

Report Generation

SCROLL moves data in a screen array up or down.

Report GenerationThere are three statements in INFORMIX-4GL that control report writing.

STARTREPORT

signals INFORMIX-4GL to initialize the report. Optionally,you can specify the output device in the START REPORTstatement.

OUTPUT TOREPORT

passes a row of the report variables to the report. This state-ment is usually found within a FOREACH loop where thereport row is the current row of a query.

FINISHREPORT

handles the end of report summaries and, if necessary, sec-ond passes through the data so that aggregate values can becalculated.

Error and Exception HandlingINFORMIX-4GL allows you to trap run-time errors and warnings, and user-entered Interrupt (usually DEL or CTRL-C) and Quit (CTRL-\) signals. Fornon-MODE ANSI databases, the default effects are that errors, Interrupts,and Quits cause immediate program termination, while warnings areignored. (In a MODE ANSI database, processing continues by default afteran error though not after an Interrupt or Quit.) You can change these defaultswith the following commands:

WHENEVER allows you to trap errors, warnings, and NOTFOUND condi-tions, and to instruct INFORMIX-4GL to call a function, go toa statement, terminate the program, or ignore the problem.In the last case (WHENEVER ERROR CONTINUE), you musttest for errors explicitly after every statement where an errorwould produce difficulties in your program.

DEFER allows you to prevent INFORMIX-4GL from terminating aprogram when the user presses the Interrupt or Quit keys. Ifyou choose this option, the Interrupt and/or Quit keys willterminate INPUT, INPUT ARRAY, CONSTRUCT, and PROMPTstatement but will not terminate the program. You mustexplicitly check the global variables int_flag and quit_flag todetermine whether the user has pressed the Interrupt orQuit keys after these statements.

INFORMIX-4GL Programming 2-21

Page 120: Manual Informix

Error and Exception Handling

Error Handling

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

Three library functions, described later in this section, are available tothe 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 theNOT FOUND condition in the execution of other statements. INFORMIX-4GLindicates errors, warnings, and NOT FOUND conditions by supplying valuesfor the global record SQLCA. See Chapter 3 for a description of the SQLCArecord, and Chapter 7 for syntax of WHENEVER.

The WHENEVER statement has the effect of writing an IF statement aftereach subsequent SQL statement in the source-code module to test for anexceptional condition, and specifies an action to take if the condition isdetected. Without a WHENEVER statement, the default action after a warningor NOT FOUND is CONTINUE. For errors, however, the default depends onyour type of database.

Your 4GL compiler identifies the database that your program declares inthe DATABASE statement that precedes the first program block (the MAINprogram block, or the first function or report program block). If this databaseis 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 nextWHENEVER ERROR statement in the module (or to the end of the module,if no more WHENEVER ERROR statements appear in the module). The scopeof reference of WHENEVER WARNING and WHENEVER NOT FOUND state-ments are similar, extending to the end of the module, or else to the nextWHENEVER statement that specifies the same condition in the same sourcecode module.

If you do not specify WHENEVER ERROR CONTINUE, then the startlog( )function causes the routine name, the error code, and the corresponding errormessage 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

Page 121: Manual Informix

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 donot want the error log file to reside in the current directory, you must specifya pathname.

Another library function, errorlog("message"), appends the quoted string orCHAR variable message to the error log. This function allows you to writedirectly to the error log file.

Chapter 6 describes these and three other 4GL library functions that dealwith errors:

err_print( ) If passed the error code, prints the message on the Error line.

err_get( ) If passed the error code, returns the message to a stringvariable.

err_quit( ) 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 andquit_flag for QUIT) is set to non-zero and can be checked by the program. Itis the programmer’s responsibility to reset the flags to zero. The default foreither an Interrupt or a Quit signal is to cause the INFORMIX-4GL program tostop immediately.

If the user enters an Interrupt during an INPUT or INPUT ARRAY statementand you have executed the DEFER INTERRUPT statement, the program con-trol 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 theDEFER QUIT statement as well.

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

INFORMIX-4GL Programming 2-23

Page 122: Manual Informix

Built-in Functions

of these concepts.) If your program inserts data into the database fromsources other than a form, you can check that the data meets these samerestrictions by using the VALIDATE statement.

VALIDATE issues an error if the value of a program variable is not con-sistent with limitations set for the corresponding column insyscolval.

If the current database is not MODE ANSI, then the upscol utility createsa single syscolval table that can specify acceptable values or ranges of valuesfor any or all database columns. The VALIDATE statement enforces thelimitations specified in this table.

In a MODE ANSI database, however, each user of upscol creates an individualowner. syscolval table. When INFORMIX-4GL subsequently processes aVALIDATE statement of the form:

VALIDATE variable-list LIKE [ owner. ] table. column

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

Built-in FunctionsIn addition to functions that you create with a FUNCTION statement and Cfunctions that you can call, INFORMIX-4GL provides a number of pre-definedfunctions, operators, and keyword expressions. You can use the followingfunctions, operators, and keywords in expressions.

ASCII MDY( )CLIPPED MONTH( )COLUMN TIMECURRENT TODAYDATE UNITSDATE( ) USINGDAY( ) WEEKDAY( )EXTEND( ) YEAR( )LENGTH( )

These are described in the sections that follow. There are additional functionsthat can be used only within REPORT program blocks (described inChapter 4) and INFORMIX-4GL library functions that cannot be used in SQLstatements (described in Chapter 6).

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

2-24 INFORMIX-4GL Programming

Page 123: Manual Informix

ASCII

ASCII

OverviewThis function evaluates an integer argument as the corresponding ASCIIcharacter.

SyntaxASCII num-expr

ExplanationASCII is a required keyword.

num-expr is a number expression.

NotesINFORMIX-4GL evaluates this function as a single character. You can use it todisplay CTRL characters.

ExamplesThe following DISPLAY statement rings the terminal bell (ASCII value of 7).

DEFINE bell CHAR(1)LET bell = ASCII 7DISPLAY bell

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

INFORMIX-4GL Programming 2-25

Page 124: Manual Informix

Examples

when it receives 9, 11, and 0, it will revert to black printing. The values usedin the example are hypothetical; refer to your printer or terminal manual forinformation on your printer or terminal.

FORMATFIRST PAGE HEADER

LET red_on = ASCII 9, ASCII 11, ASCII 1LET 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 ASCIIcharacters. Be sure to account for the non-printing characters when using theCOLUMN function to format your page. Since various devices differ in outputtingspaces with CTRL characters, you may have to use trial and error to line up columnswhen you output CTRL characters.

2-26 INFORMIX-4GL Programming

Page 125: Manual Informix

CLIPPED

CLIPPED

OverviewCLIPPED displays the character expression that precedes it without anytrailing blanks.

Syntaxchar-expr CLIPPED

Explanationchar-expr is a required character expression.

CLIPPED is a required keyword.

Notes1. 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 anexpression. CLIPPED does not affect the value when it is stored in avariable (unless you are concatenating CLIPPED values together).

For example, if CHAR variable b contains a string that is shorter than the datatype of a, the following LET statement pads a with trailing blanks, despite theCLIPPED keyword:

LET a = b CLIPPED

The following statement displays b without trailing blanks:

DISPLAY b CLIPPED AT 1,12

INFORMIX-4GL Programming 2-27

Page 126: Manual Informix

Example

ExampleThe following example is from a REPORT program block that prints mailinglabels.

FORMATON EVERY ROW

IF (city IS NOT NULL)AND (state IS NOT NULL) THENPRINT fname CLIPPED, 1 SPACE, lnamePRINT companyPRINT address1IF (address2 IS NOT NULL) THEN

PRINT address2END IF

PRINT city CLIPPED, " , " , state,2 SPACES, zipcodeSKIP TO TOP OF PAGE

END IF

2-28 INFORMIX-4GL Programming

Page 127: Manual Informix

COLUMN

COLUMN

OverviewThe COLUMN function returns a string of spaces long enough to beginthe next item in the designated column.

SyntaxCOLUMN integer-expr

ExplanationCOLUMN is a required keyword.

integer-expr is a required positive integer expression that specifies the ini-tial column number of the next item to be printed.

Notes1. In REPORT program blocks, INFORMIX-4GL calculates the column

number by adding integer-expr to the left margin that you set in theOUTPUT section. Otherwise, the column number is counted fromthe left edge of your screen.

2. If INFORMIX-4GL has already printed past the column specified byinteger-expr, INFORMIX-4GL ignores the COLUMN expression.

3. If you use the COLUMN function in a DISPLAY statement, you mustspecify an integer instead of an integer expression after the COLUMNkeyword.

ExamplePAGE HEADER

PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35,"CITY", COLUMN 57, "ZIP", COLUMN 65, "PHONE"

SKIP 1 LINEON 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

Page 128: Manual Informix

CURRENT

CURRENT

OverviewThe CURRENT function returns a DATETIME value with the date and time ofday of the current instant.

SyntaxCURRENT [ first TO last ]

ExplanationCURRENT is a required keyword.

first is a qualifier that specifies the first field to be returned.

TO is a required keyword if you specify first and last.

last is a qualifier that specifies the last field to be returned.

Notes1. 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 aDATETIME literal.

3. The first qualifier must specify a field that is more significant than or equalto the last qualifier.

4. If the function is executed more than once in a statement, identical valuesmay be returned at each point of the call. You cannot rely on CURRENT toprovide distinct values each time that it executes in the same statement.

5. INFORMIX-4GL may not execute the CURRENT function in the physicalorder in which it appears in a statement. You should not use the functionto mark the start, the end, or any specific point in the execution of the 4GLstatement.

6. If no first TO last qualifiers are specified, the default qualifiers areYEAR TO FRACTION(3).

2-30 INFORMIX-4GL Programming

Page 129: Manual Informix

Examples

7. The following qualifiers are valid:

Identifier Qualified DataYEAR A number of years.MONTH A number of months.DAY A number of days.HOUR A number of hours.MINUTE A number of minutes.SECOND A number of seconds.FRACTION (n) A decimal fraction of a second with n (up to 5) digits of

precision. The default precision is 3 digits (thousandths ofa second).

Examples-- SQL statement

SELECT prog_title from tv_programs whereair_date > CURRENT YEAR TO DAY

ATTRIBUTES -- FORM4GL fieldtimestamp = formonly.tmstmp type DATETIME HOUR TO SECOND,

default = CURRENT HOUR TO SECOND;

PAGE HEADER -- Report control blockprint 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 executionspanned midnight.

INFORMIX-4GL Programming 2-31

Page 130: Manual Informix

DATE

DATE

OverviewThe DATE function returns a character string that has the format ‘‘Wed Sep 201989’’ and whose value is the current date.

SyntaxDATE

ExplanationDATE is a required keyword.

NoteThis function reads the current date from the system clock.

ExampleThe 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

Page 131: Manual Informix

DATE( )

DATE( )

OverviewThe DATE( ) function returns a type DATE value, corresponding to the expres-sion with which you call it.

SyntaxDATE ( expr )

ExplanationDATE is a required keyword.

expr is a required expression that can be converted to a type DATEvalue.

NoteThe expr is usually of type CHAR, DATETIME, or INTEGER.

ExamplesThe 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

Page 132: Manual Informix

DAY( )

DAY( )

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

SyntaxDAY ( dtime-expr )

ExplanationDAY is a required keyword.

dtime-expr is a required expression whose value is of type DATE orDATETIME.

ExamplesThe first example extracts the day of the month from a DATETIME literalexpression:

DEFINE d_var INTEGER,date_var DATETIME YEAR TO SECOND

LET date_var = DATETIME (89-12-09 18:47:32) YEAR TO SECONDLET 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 todisplay 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

Page 133: Manual Informix

EXTEND( )

EXTEND( )

OverviewThe EXTEND function adjusts the precision of a DATETIME value.

SyntaxEXTEND ( value [ , first TO last ] )

ExplanationEXTEND is a required keyword.

value is a DATE or DATETIME value (column name, variable, or expres-sion) of any valid precision.

first is an optional qualifier that specifies the first field in the result.(See Note 5.)

TO is a required keyword if you include first and last qualifiers.

last is an optional qualifier that specifies the last field in the result. (SeeNote 6.)

Notes1. The value can also be a DATETIME literal, or a character string that consists

of valid and unambiguous DATETIME values and separators. It cannot bea string constant in DATE format.

2. If no first TO last qualifiers are specified, the default qualifiers are YEARTO FRACTION(3).

3. The first qualifier must specify a field that is more significant than or equalto the last qualifier.

4. If the value contains fields not specified by the qualifiers, the unwantedfields are discarded.

5. If the first qualifier specifies a field to the left of (that is, more significantthan) what exists in value, the new fields are filled with values returnedby the CURRENT function.

6. If the last qualifier specifies a field to the right of (that is, less significantthan) what exists in value, the new fields are filled in with constant values.

INFORMIX-4GL Programming 2-35

Page 134: Manual Informix

Examples

A missing MONTH or DAY is filled in with 1, and the missing fields HOURto FRACTION are filled in with 0.

7. The following qualifiers are valid:

Identifier Qualified DataYEAR A number of years.MONTH A number of months.DAY A number of days.HOUR A number of hours.MINUTE A number of minutes.SECOND A number of seconds.FRACTION (n) A decimal fraction of a second with n (up to 5) digits of

precision. The default precision is 3 digits (thousandths ofa second)

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

ExamplesIn the first example, the EXTEND function returns the MONTH and DAY fieldsfrom 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; itretains the MONTH, DAY, and HOUR values that are already in start_date, andit 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 fieldsthat are not present in the DATETIME variable t_stamp, so the EXTEND func-tion is required in the expression that calculates the sum of their values.

DEFINE t_stamp DATETIME YEAR TO HOURDEFINE age DATETIME DAY TO MINUTEDEFINE how_old INTERVAL DAY TO MINUTE

LET t_stamp = "1989-12-04 17"LET how_old = INTERVAL (28 9:25) DAY TO MINUTELET age = EXTEND(t_stamp, DAY TO MINUTE) + how_old

2-36 INFORMIX-4GL Programming

Page 135: Manual Informix

Examples

Appendix J, “Working with DATETIME and INTERVAL Data,” providesmore information on using date and time expressions with arithmeticoperators.

INFORMIX-4GL Programming 2-37

Page 136: Manual Informix

LENGTH( )

LENGTH( )

OverviewThis function returns the number of bytes in its string argument after deletingall trailing spaces.

SyntaxLENGTH ( str )

Explanationstr is a string constant, CHAR variable, or database column.

Notes1. In a SELECT or UPDATE statement, with str the identifier of a character

column, this function returns the number of bytes in the CLIPPED datavalue.

2. The LENGTH function must be within an SQL statement if str is a databasecolumn.

ExamplesThese statements center a report title on an 80-column page:

LET title = "Invoice for ", fname CLIPPED," ", lname CLIPPED

LET offset = (80 - length(title))/2PRINT COLUMN offset, title

The next statement retrieves the value in column1 and the length in bytes ofthe string in column2 (excluding trailing blanks).

SELECT column1, LENGTH(column2) FROM mytable

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

2-38 INFORMIX-4GL Programming

Page 137: Manual Informix

MDY( )

MDY( )

OverviewThe MDY( ) function returns a type DATE value when you call it with threeexpressions that evaluate to integers representing the month, day of themonth, and year.

SyntaxMDY ( expr1, expr2, expr3 )

ExplanationMDY is a required keyword.

expr1 is an expression that evaluates to an integer representing the num-ber of the month (1-12).

expr2 is an expression that evaluates to an integer representing the num-ber of the day of the month (1-28, 29, 30, or 31, depending on themonth).

expr3 is an expression that evaluates to a four-digit integer representingthe year.

Notes1. Enclose the list of integer expressions expr1, expr2, and expr3 in parenthe-

ses, 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

Page 138: Manual Informix

MONTH( )

MONTH( )

OverviewThe MONTH( ) function returns an integer corresponding the month portionof its type DATE or DATETIME argument.

SyntaxMONTH ( dtime-expr )

ExplanationMONTH is a required keyword.

dtime-expr is a required expression of type DATE or DATETIME.

Notes1. This function extracts the month from a DATE or DATETIME value, return-

ing an integer m in the range 1 <= m <= 12.

2. The dtime-expr cannot be an INTERVAL argument.

ExamplesIf the program variable then contains a DATE or DATETIME value, the Bool-ean expression

MONTH(then) > 9

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

2-40 INFORMIX-4GL Programming

Page 139: Manual Informix

TIME

TIME

OverviewTIME evaluates as a character string whose value is the current time-of-dayfrom the system clock.

SyntaxTIME

ExplanationTIME is a required keyword.

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

ExampleDEFINE p_time char(15)LET p_time = TIME

DISPLAY "The time is ", p_time

INFORMIX-4GL Programming 2-41

Page 140: Manual Informix

TODAY

TODAY

OverviewTODAY evaluates as type DATE with a value of the current date, as suppliedby the operating system.

SyntaxTODAY

ExplanationTODAY is a required keyword.

ExampleThe following example is from a REPORT program block:

SKIP 1 LINEPRINT 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 LINESPRINT COLUMN 2, "ORDER DATE", COLUMN 15, "COMPANY",

COLUMN 35, "NAME", COLUMN 57, "NUMBER",COLUMN 65, "AMOUNT"

2-42 INFORMIX-4GL Programming

Page 141: Manual Informix

UNITS

UNITS

OverviewThe UNITS keyword returns an INTERVAL value with one qualifier.

Syntaxexpr UNITS qualifier

Explanationexpr is a number expression.

UNITS is a required keyword.

qualifier is the name of an INTERVAL field.

Notes1. 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 sub-tracted from a DATETIME or INTERVAL expression, provided that theUNITS operand follows the arithmetic operator (either + or - ) as the sec-ond operand.

3. The qualifier can be any one of the following field keywords:

YEAR MONTH DAYHOUR MINUTE SECOND FRACTION ( n )

ExampleLET fortnite = CURRENT + 14 UNITS DAY

INFORMIX-4GL Programming 2-43

Page 142: Manual Informix

USING

USING

OverviewThe USING operator specifies a format for number, MONEY, or DATE expres-sions. With a number or MONEY expression, you can use USING to line updecimal points or currency symbols, to right- or left-justify numbers, to putnegative numbers in parentheses, and to perform other formatting tasks.USING can convert a DATE value to a variety of formats.

Syntaxexpr USING "format-string"

Explanationexpr is a required expression that specifies what USING is to

format.

USING is a required keyword.

format-string is a required quoted string that specifies how USING is toformat expr.

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 asingle character as far to the right as possible, without interfering with thenumber that is being displayed. Refer to the following list for an explanationof these characters.

* This character fills with asterisks ( * ) any positions in the displayfield that would otherwise be blank.

& This character fills with zeros any positions in the display fieldthat would otherwise be blank.

# This character does not change any blank positions in the displayfield. 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 (butdisplays no comma unless there is a number to the left of it).

2-44 INFORMIX-4GL Programming

Page 143: Manual Informix

Explanation

. This character is a literal. USING displays it as a period. You canonly have one period in a format string.

- This character is a literal. USING displays it as a minus sign whenexpr is less than zero, and otherwise as a blank. When you groupseveral minus signs in a row, a single minus sign floats to therightmost position without interfering with the number beingprinted.

+ This character is a literal. USING displays it as a plus sign whenexpr is greater than or equal to zero, and as a minus sign when itis less than zero. When you group several plus signs in a row, asingle plus sign floats to the rightmost position without interfer-ing with the number being printed.

( This character is a literal. USING displays it as a left parenthesisbefore a negative number. It is the accounting parenthesis that isused in place of a minus sign to indicate a negative number. Whenyou group several parentheses in a row, a single left parenthesisfloats to the rightmost position without interfering with the num-ber being printed.

) This is the accounting parenthesis that is used in place of a minussign to indicate a negative number. One of these characters gener-ally closes a format string that begins with a left parenthesis.

$ This character is a literal. USING displays it as a dollar sign. Whenyou group several dollar signs in a row, a single dollar sign floatsto the rightmost position without interfering with the numberbeing printed.

Refer to the ‘‘Examples’’ section for examples of formatting number expres-sions. Since format strings interact with data to produce visual effects, somereaders may find that the examples are easier to follow than the descriptionsof format string characters listed previously.

INFORMIX-4GL Programming 2-45

Page 144: Manual Informix

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 thefollowing examples.)dd day of the month as a 2-digit number (01-31)ddd day of the week as a 3-letter abbreviation (Sun through Sat)

mm month as a 2-digit number (01-12)mmm month as a 3-letter abbreviation (Jan through Dec)

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

Figure 2-1 Combinations of DATE Format Strings

Notes1. The format-string must appear between quotation ( " ) marks.

2. Although USING is generally used as part of a DISPLAY or PRINTstatement, 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.

ExamplesThe following example prints the balance field using a format string thatallows 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 value23,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 providesblank fill for unused character positions, while the & character provides zerofilling. This format ensures that even if the number is zero, any positionsmarked 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

Page 145: Manual Informix

Examples

the currency symbol floats with the size of the number, so that it appearsimmediately to the left of the most significant digit in the display, as shownhere:

The current balance is $23,485.23

The following examples show valid conversions for December 25, 1989:

Format String Formatted Result"mmddyy" 122589"ddmmyy" 251289"yymmdd" 891225"yy/mm/dd" 89/12/25"yy mm dd" 89 12 25"yy-mm-dd" 89-12-25"mmm. dd, yyyy" Dec. 25, 1989"mmm dd yyyy" Dec 25 1989"yyyy dd mm" 1989 25 12"mmm dd yyyy" Dec 25 1989"ddd, mmm. dd, yyyy" Mon, Dec. 25, 1989"(ddd) mmm. dd, yyyy" (Mon) Dec. 25, 1989

The following example is from a REPORT program block:

ON LAST ROWSKIP 2 LINESPRINT "Number of customers in ", state, " are ",

COUNT(*) USING "<<<<<"

PAGE TRAILERPRINT COLUMN 35, "page ", PAGENO USING "<<<<"

INFORMIX-4GL Programming 2-47

Page 146: Manual Informix

Examples

The following example is from a more complex REPORT program block andillustrates several different formats:

SKIP 1 LINEPRINT 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 linesPRINT COLUMN 2, "ORDER DATE", COLUMN 15, "COMPANY",

COLUMN 35, "NAME", COLUMN 57, "NUMBER",COLUMN 65, "AMOUNT"

BEFORE GROUP OF daysSKIP 2 LINES

AFTER GROUP OF numberPRINT 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 daysSKIP 1 LINEPRINT COLUMN 21, "Total amount ordered for the day: ",

GROUP SUM (total_price) USING "$$$$,$$$,$$$.&&"SKIP 1 LINEPRINT COLUMN 15,

"====================================================="

ON LAST ROWSKIP 1 LINEPRINT COLUMN 15,

"======================================================"SKIP 2 LINESPRINT "Total Amount of orders: ", SUM (total_price)

USING "$$$$,$$$,$$$.&&"

PAGE TRAILERPRINT COLUMN 28, PAGENO USING "page <<<<"

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

2-48 INFORMIX-4GL Programming

Page 147: Manual Informix

Examples

Format String Data Value Formatted Result

"#####" 0 bbbbb"&&&&&" 0 00000"$$$$$" 0 bbbb$"*****" 0 *****"<<<<<" 0 bbbbb

(null string)

"<<<,<<<" 12345 12,345"<<<,<<<" 1234 1,234"<<<,<<<" 123 123"<<<,<<<" 12 12

"##,###" 12345 12,345"##,###" 1234 b1,234"##,###" 123 bbb123"##,###" 12 bbbb12"##,###" 1 bbbbb1"##,###" -1 bbbbb1"##,###" 0 bbbbbb

"&&,&&&" 12345 12,345"&&,&&&" 1234 01,234"&&,&&&" 123 000123"&&,&&&" 12 000012"&&,&&&" 1 000001"&&,&&&" 0 000000

"$$,$$$" 12345 ******(overflow)

"$$,$$$" 1234 $1,234"$$,$$$" 123 bb$123"$$,$$$" 12 bbb$12"$$,$$$" 1 bbbb$1"$$,$$$" 0 bbbbb$

"**,***" 12345 12,345"**,***" 1234 *1,234"**,***" 123 ***123"**,***" 12 ****12"**,***" 1 *****1"**,***" 0 ******

Here the character b represents a blank or space.

INFORMIX-4GL Programming 2-49

Page 148: Manual Informix

Examples

Format String Data Value Formatted Result

"##,###.##" 12345.67 12,345.67"##,###.##" 1234.56 b1,234.56"##,###.##" 123.45 bbb123.45"##,###.##" 12.34 bbbb12.34"##,###.##" 1.23 bbbbb1.23"##,###.##" 0.12 bbbbb0.12"##,###.##" 0.01 bbbbbb.01"##,###.##" -0.01 bbbbbb.01"##,###.##" -1 bbbbb1.00

"&&,&&&.&&" 12345.67 12,345.67"&&,&&&.&&" 1234.56 01,234.56"&&,&&&.&&" 123.45 000123.45"&&,&&&.&&" 0.01 000000.01

"$$,$$$.$$" 12345.67 *********(overflow)

"$$,$$$.$$" 1234.56 $1,234.56"$$,$$$.##" 0.00 $.00"$$,$$$.##" 1234.00 $1,234.00"$$,$$$.&&" 0.00 $.00"$$,$$$.&&" 1234.00 $1,234.00

"-##,###.##" -12345.67 -12,345.67"-##,###.##" -123.45 -bbb123.45"-##,###.##" -12.34 -bbbb12.34"--#,###.##" -12.34 -bbb12.34"---,###.##" -12.34 -bb12.34"---,-##.##" -12.34 -12.34"---,--#.##" -1.00 -1.00

"-##,###.##" 12345.67 12,345.67"-##,###.##" 1234.56 1,234.56"-##,###.##" 123.45 123.45"-##,###.##" 12.34 12.34"--#,###.##" 12.34 12.34"---,###.##" 12.34 12.34"---,-##.##" 12.34 12.34"---,---.##" 1.00 1.00"---,---.--" -.01 -.01

Here the character b represents a blank or space.

2-50 INFORMIX-4GL Programming

Page 149: Manual Informix

Examples

Format String Data Value Formatted Result

"----,---.&&" -.01 -.01"-$$$,$$$.&&" -12345.67 -$12,345.67"-$$$,$$$.&&" -1234.56 -b$1,234.56"-$$$,$$$.&&" -123.45 -bbb$123.45"--$$,$$$.&&" -12345.67 -$12,345.67"--$$,$$$.&&" -1234.56 -$1,234.56"--$$,$$$.&&" -123.45 -bb$123.45"--$$,$$$.&&" -12.34 -bbb$12.34"--$$,$$$.&&" -1.23 -bbbb$1.23

"----,--$.&&" -12345.67 -$12,345.67"----,--$.&&" -1234.56 -$1,234.56"----,--$.&&" -123.45 -$123.45"----,--$.&&" -12.34 -$12.34"----,--$.&&" -1.23 -$1.23"----,--$.&&" -.12 -$.12

"$***,***.&&" 12345.67 $*12,345.67"$***,***.&&" 1234.56 $**1,234.56"$***,***.&&" 123.45 $****123.45"$***,***.&&" 12.34 $*****12.34"$***,***.&&" 1.23 $******1.23"$***,***.&&" .12 $*******.12

"($$$,$$$.&&)" -12345.67 ($12,345.67)"($$$,$$$.&&)" -1234.56 (b$1,234.56)"($$$,$$$.&&)" -123.45 (bbb$123.45)"(($$,$$$.&&)" -12345.67 ($12,345.67)"(($$,$$$.&&)" -1234.56 ($1,234.56)"(($$,$$$.&&)" -123.45 (bb$123.45)"(($$,$$$.&&)" -12.34 (bbb$12.34)"(($$,$$$.&&)" -1.23 (bbbb$1.23)

"((((,(($.&&)" -12345.67 ($12,345.67)"((((,(($.&&)" -1234.56 ($1,234.56)"((((,(($.&&)" -123.45 ($123.45)"((((,(($.&&)" -12.34 ($12.34)"((((,(($.&&)" -1.23 ($1.23)"((((,(($.&&)" -.12 ($.12)

Here the character b represents a blank or space.

INFORMIX-4GL Programming 2-51

Page 150: Manual Informix

Examples

Format String Data Value Formatted Result

"($$$,$$$.&&)" 12345.67 $12,345.67"($$$,$$$.&&)" 1234.56 $1,234.56"($$$,$$$.&&)" 123.45 $123.45"(($$,$$$.&&)" 12345.67 $12,345.67"(($$,$$$.&&)" 1234.56 $1,234.56"(($$,$$$.&&)" 123.45 $123.45"(($$,$$$.&&)" 12.34 $12.34"(($$,$$$.&&)" 1.23 $1.23

"((((,(($.&&)" 12345.67 $12,345.67"((((,(($.&&)" 1234.56 $1,234.56"((((,(($.&&)" 123.45 $123.45"((((,(($.&&)" 12.34 $12.34"((((,(($.&&)" 1.23 $1.23"((((,(($.&&)" .12 $.12

Here the character b represents a blank or space.

2-52 INFORMIX-4GL Programming

Page 151: Manual Informix

WEEKDAY( )

WEEKDAY( )

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

SyntaxWEEKDAY ( dtime-expr )

ExplanationWEEKDAY is a required keyword.

dtime-expr is a required expression of type DATE.

Notes1. 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.

ExampleLET tag = WEEKDAY(p_orders.order_date)

INFORMIX-4GL Programming 2-53

Page 152: Manual Informix

YEAR( )

YEAR( )

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

SyntaxYEAR ( dtime-expr )

ExplanationYEAR is a required keyword.

dtime-expr is a required expression of type DATE or DATETIME.

NoteThe dtime-expr cannot be an INTERVAL argument.

ExampleLET y_var = YEAR(TODAY)

2-54 INFORMIX-4GL Programming

Page 153: Manual Informix

C Functions

C FunctionsINFORMIX-4GL programs can call C language functions. To provide a trans-parent function-calling mechanism, INFORMIX-4GL requires that C functionsfollow a calling convention that allows data to be passed between the INFOR-MIX-4GL program and the C function.

This calling convention that is described in this section applies to both theC Compiler Version and Rapid Development System implementations ofINFORMIX-4GL. If you have the Rapid Development System, see also thesection“RDS Programs That Call C Functions” in Chapter 1, which describesthe additional procedures that are required to compile and run suchprograms.

The convention uses a stack, which is a data structure that can be accessed ina predefined way by both INFORMIX-4GL programs and C functions. Youcan perform two classes of operations on a stack:

push to add a variable to the stack

pop to retrieve a variable from the stack

The stack acts as a LIFO (last-in, first-out) queue. The variable added to thestack by the last push is the next variable to be removed from the stack if youdo a pop. The next page lists functions that are provided with INFORMIX-4GLto 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 leftto 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 conventionrequires INFORMIX-4GL to automatically pass the number of calling param-eters as the only real argument to the C function. This tells the C function howmany values to pop.

The C functions designed to work with INFORMIX-4GL must obey the callingconvention by complementing the actions of INFORMIX-4GL. All compatibleC functions have only one argument, which is the number of parameters thatINFORMIX-4GL placed on the stack. You use this argument to pop the callingparameters. INFORMIX-4GL supplies the following library of functions toassist this process.

INFORMIX-4GL Programming 2-55

Page 154: Manual Informix

C Functions

Popping Functions Pushing Functions Argument Typespopint(&i) retint(i) int i;popshort(&s) retshort(s) short s;poplong(&l) retlong(l) long l;popflo(&f) retflo(&f) float f;popdub(&d) retdub(&d) double d;popquote(str, len) retquote(str) char *str;

int len;popdec(&dm) retdec(&dm) dec_t dm;popdtime(&dt, qual) retdtime(&dt) dtime_t dt;

int qual;popinv(&inv, qual) retinv(&inv) intrvl_t inv;

int qual;

Note: INFORMIX-OnLine supports additional functionality. Refer to theINFORMIX-OnLine Programmer’s Manual for more information.

Here len is the buffer size of the string to which str points, and qual is the qual-ifier of the DATETIME or INTERVAL value that will be received by destinationvariable dt or inv.

Your first step in a C function is to pop all the arguments in the reverse orderfrom the order in the call. If the call is to myfunc, you must first pop c, andthen b, and finally a. You must use the library function that is appropriate forthe data type of the receiving variable. After the function is called, INFOR-MIX-4GL restores the stack pointer to its original state.

To return values from the C function to the INFORMIX-4GL program, youmust push the values onto the stack. They must be pushed in the same orderas 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 thepush. 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 innumber and in data type, the argument list in the RETURNING clause of theINFORMIX-4GL statement. If you do not return the correct data types, yourprogram can execute unpredictably. Failure to return the expected number ofarguments causes an error.

2-56 INFORMIX-4GL Programming

Page 155: Manual Informix

Examples

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

• 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 allowfor that in the value of m.

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

ExamplesThe first example (which only schematically represents actual C code) showsthe basic structure for C functions that you can call from an INFORMIX-4GLprogram.

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

Page 156: Manual Informix

Examples

The following INFORMIX-4GL program calls the C language functionsndmsg, which converts a string into EBCDIC and sends it to a remote com-puter. Two arguments are explicitly passed to the function: the source stringand its length. INFORMIX-4GL automatically passes the number of argu-ments 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 arepassed. INFORMIX-4GL cannot guarantee recovery of the stack if a functionis called with the wrong number of arguments, since that is a failure to followthe calling convention between INFORMIX-4GL and C functions. Thesndmsg function terminates the program if the wrong number of argumentsis passed.

2-58 INFORMIX-4GL Programming

Page 157: Manual Informix

Examples

If the correct number of arguments is passed, sndmsg pops the argumentsfrom the stack, using the library functions appropriate for the data type. Anannotated listing of the sndmsg program follows:

#include "stdio.h"#include "decimal.h"sndmsg(nargs)

/* 4gl syntax is CALL sndmsg (input,len) RETURNING msg_number, retcode */

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

{

char input[80]; /* 4gl and C function must agree on data */int msg_number; /* types and the order that arguments are */int len, retcode; /* placed on the stack */

/* 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 func-tions for the data type and pushes return arguments onto the stack from leftto right. The last statement executed by the function returns the number of

INFORMIX-4GL Programming 2-59

Page 158: Manual Informix

Examples

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

2-60 INFORMIX-4GL Programming

Page 159: Manual Informix

Chapter

3

Using SQLChapter Overview 5

Relational Databases 5

SQL Identifiers 6Owner Naming 7

Database Data Types 8

SQL Statement Summary 10

Data Definition 11

Data Manipulation 12

Cursor Management 13SELECT Cursors 13

Associating a Cursor with a SELECT Statement 14Retrieving and Processing Rows 15The SCROLL Cursor 20The Cursor WITH HOLD 23

INSERT Cursors 25

Dynamic Management 28Preparing Statements 29

Statements That Require No Input 30Statements That Require Input for Values 30Statements That Require Input

for SQL Identifiers 32Executing PREPAREd Statements 33

The EXECUTE Statement 33Running PREPAREd SELECT Statements 35Running PREPAREd INSERT Statements 37

Preparing Multiple SQL Statements 38The FREE Statement 39

Page 160: Manual Informix

Data Access 40

User Status and Privileges 41

Data Integrity 42Transactions 42

Databases Without Transactions 43Databases with Implicit Transactions 43Databases with Explicit Transactions 44Using Transactions 44

Transaction Log File Maintenance 45Audit Trails 45

Creating an Audit Trail 46Recovering a Table 46

Comparison of Transactions and Audit Trails 47

Locking 47Row-Level Locking 48

Row-Level Locking in Transactions 49Table-Level Locking 49Wait for Locked Row 50

Indexing Strategy 50Query Optimizer 52Auto-Indexing 52Clustered Indexes 52

NULL Values 53Default Values 54The NULL in Expressions 54The NULL in Boolean Expressions 55The NULL in WHERE Clauses 55The NULL in ORDER BY Clauses 56The NULL in GROUP BY Clauses 56The NULL Keyword in INSERT and UPDATE Statements 57

Views 57Creating and Deleting Views 58Querying Through Views 58Modifying Through Views 59Privileges with Views 60Data Constraints Using Views 60

3-2 Using SQL

Page 161: Manual Informix

Outer Joins 61

Table Access by ROWID 62

SQLCA Record 63

TODAY, CURRENT, and USER Functions 65

Using SQL 3-3

Page 162: Manual Informix

3-4 Using SQL

Page 163: Manual Informix

Chapter OverviewInformix Software, Inc. has developed an implementation of SQL thatextends the Structured Query Language (SQL) developed by IBM. The Infor-mix Software additions to the language permit you to change databases, tochange the names of tables and columns, and to increase the functionality ofANSI 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 lan-guage you use to choose the data for ACE, the INFORMIX-SQL report-writingprogram. You can read about these uses of SQL in the INFORMIX-SQL UserManual. In INFORMIX-ESQL/C, SQL is the database query language that youembed in C programs to create an application. In INFORMIX-4GL, SQL state-ments are combined with those described in Chapter 2 to form an almostseamless fourth-generation language.

This chapter describes SQL and gives an overview of its statements. The fullsyntax and rules governing SQL statements are located in Chapter 7 of theINFORMIX-4GL Reference Manual.

Relational DatabasesSQL statements create and manipulate relational databases. A relationaldatabase consists of one or more tables that, in turn, are constructedof rows and columns. Each row contains a specific set of column values.

Databases are created as subdirectories of the current directory. The nameof the directory is the database name with the extension .dbs.

The database subdirectory contains 11 system catalog tables that define thedatabase dictionary. It also contains the tables that constitute the database.Each of these tables is represented by data files and index files, with theextensions .dat and .idx, respectively. The system catalogs are describedin Appendix B.

Using SQL 3-5

Page 164: Manual Informix

SQL Identifiers

You have the option of specifying a MODE ANSI database. A database createdor started as MODE ANSI supports implicit transactions and enforces owner-naming. (See the section “Data Integrity” for more information about trans-actions in a MODE ANSI database. See the section “Owner Naming” for moreinformation about owner-naming.)

INFORMIX-4GL provides several ways to check for Informix extensions to theANSI standard for SQL syntax in your programs:

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

• INFORMIX-4GL issues a run-time warning by setting the characterSQLCA.SQLAWARN [6] to W, if a program executes a statement thatincludes an Informix extension to ANSI syntax, and the DBANSIWARNenvironment variable is defined (as described in Appendix C.)

See “INFORMIX-4GL Extensions to ANSI Syntax” in Chapter 7 for a listof the Informix extensions to the ANSI standard.

SQL IdentifiersAn SQL identifier is the name of an object. It can consist of letters, numbers,and underscores ( _ ). The first character must be a letter. Unless otherwiseindicated, an identifier can have from one to 18 characters.

Database A database name is an identifier that can have from one to 10characters.

Table A table name is an identifier that must be unique within thedatabase. (In a MODE ANSI database, the owner and tablecombined must be unique within the database.)

Column A column name is an identifier that must be unique within atable; there can be duplicate column names within a data-base. When column names within different tables are notunique, use the notation table.column to specify the intendedcolumn. If you intend to define an INFORMIX-4GL recordlike a table, the first 8 characters of each column name in thetable must be unique within the table.

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

3-6 Using SQL

Page 165: Manual Informix

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 referto the database column of the same name, use @lname for the column name:

SELECT @lname INTO lname FROM customer

Owner NamingIn 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 ofthe 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 beginwith a letter. It can contain underscores, letters, and numbers, and can beup to 8 characters long. Alternatively, the name can be a quoted string.This allows you to preserve uppercase characters in user names or toinclude a user name in which the first character is a digit. The quotedstring 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 own-ership 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 anobject and assign ownership of the object to another user.

In a database created as MODE ANSI, you must specify owner when referringto an object created by another user. As with non-MODE ANSI databases, youmay specify owner when referring to your own objects.

In the following example, the UPDATE statement modifies rows in the stocktable owned by the user james:

UPDATE james.stockSET price = price * 1.05

Using SQL 3-7

Page 166: Manual Informix

Database Data Types

Quoted strings allow you to retain case sensitivity when case is important. Inthe following examples, the SELECT statements retrieve rows from differenttables:

SELECT * FROM "Smith".stockSELECT * FROM Smith.stock

Note that "Smith" is in quotes in the first SELECT statement but not in the sec-ond. Because of the quotes, the case distinction is preserved in the firstSELECT; therefore, the first SELECT retrieves rows from the Smith.stock tablewhile 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 theowner prefix. As the owner of the system catalog tables is informix, you mustinclude the owner name informix when querying each system catalog.

You do not have to supply owner names when working with a non-MODEANSI database. However, if you specify the owner along with the objectname, 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 theowner.object naming convention to refer to an object owned by another user. If youstart a database as MODE ANSI, you must modify existing queries that reference atable, view, or synonym owned by another user to include the owner prefix.

Database Data TypesYou must assign a data type to every column in the database. (See theCREATE TABLE statement in Chapter 7). Except for the SERIAL data type, theSQL data types are identical to the corresponding 4GL data types that weredefined in Chapter 2. The valid SQL data types are as follows:

CHAR [(n)] is a character string of length n (where 1 ≤ n ≤ 32,511).If you do not specify n, CHAR(1) is assumed.

CHARACTER is a synonym for CHAR.

SMALLINT is a whole number from -32,767 to +32,767.

INTEGER is a whole number from -2,147,483,647 to+2,147,483,647.

INT is a synonym for INTEGER.

DECIMAL [(m[,n])] is a decimal floating point number with m (≤ 32)significant digits (the precision) and n (≤ m) digitsright of the decimal point (the scale). When you givevalues for both m and n, the decimal variable hasfixed-point arithmetic. All numbers with an absolute

3-8 Using SQL

Page 167: Manual Informix

Database Data Types

value less than 0.5 × 10-n have the value zero. Thelargest absolute value of a DECIMAL variable that canbe stored without an error is 10m-n - 10-n.

The second parameter is optional and, if missing, thevariable is treated as a floating decimal. DECIMAL(m)variables have a precision of and a range in absolutevalue from 10-128 to 10126 If no parameters are desig-nated, DECIMAL is treated as DECIMAL(16), a floatingdecimal.

DEC is a synonym for DECIMAL.

NUMERIC is another synonym for DECIMAL.

SMALLFLOAT is a floating-point number corresponding to the floatC data type. The range of values for a SMALLFLOATdata type is the same as the range of values for theC float data type on your machine.

REAL is a synonym for SMALLFLOAT.

FLOAT [(n)] is a floating-point number corresponding to thedouble C data type. The range of values for a FLOATdata type is the same as the range of values for theC double data type on your machine.

You can use n (where n is a whole number between1 and 14) to specify the precision of a FLOAT datatype. INFORMIX-4GL does not use the precision,however. (The optional precision parameter is pro-vided for compatibility with ANSI standards.)

DOUBLE PRECISION is a synonym for FLOAT.

MONEY [(m [,n] )] 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 toDECIMAL (16, 2). Regardless of the number of param-eters, the data type MONEY is always treated as afixed decimal number.

SERIAL [ (n) ] is a sequential integer assigned automatically byINFORMIX-4GL. You can assign an initial value n.The default starting integer is 1.

DATE is a date entered as a character string in one of the for-mats described in Chapter 2, and stored as an integernumber of days since December 31, 1899.

Using SQL 3-9

Page 168: Manual Informix

SQL Statement Summary

DATETIMEfirst TO last

stores a moment in time with the precision first to last.A DATETIME column is entered as a character stringin one of the formats described in Chapter 2, record-ing the value of a calendar date and time of day. It isstored internally as a DECIMAL number, whose digitsrepresent a contiguous sequence of the followingfields: YEAR, MONTH, DAY, HOUR, MINUTE,SECOND, and FRACTION(n) of a second. DATETIMEis described in greater detail in Appendix J.

INTERVALfirst TO last

stores a span of time with the precision first to last. AnINTERVAL column is entered as a character string inone of the formats described in Chapter 2, recordingthe value of the difference between two DATETIMEvalues. It is stored internally as a DECIMAL number,whose digits represent values of the fields from first tolast. An INTERVAL column consists of a contiguoussequence 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 inAppendix J.

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

SQL Statement SummarySix 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

Page 169: Manual Informix

Data Definition

Data DefinitionData definition statements include those that create and drop a databaseand its tables, views, and indexes, modify tables, indexes, and columns,or rename tables and columns. Of this list, only the DATABASE statementis required before manipulating the data of an existing database or definingprogram variables LIKE columns in the database.

CREATEDATABASE

creates a database directory, sets up the system catalogs, andmakes the new database the current database. There can be nomore than one current database at any time.

DATABASE selects a database and makes it the current database. Therecan be no more than one current database at any time.

CLOSEDATABASE

closes the current database files and leaves no databasecurrent. The only SQL statements permitted when thereis no current database are:

• CREATE DATABASE

• DATABASE

• DROP DATABASE

• START DATABASE

DROPDATABASE

deletes all tables, indexes, and system catalogs. If no otherfiles are present in the database subdirectory, the subdirec-tory is also deleted.

CREATETABLE

creates a table and defines the columns and their data types.

ALTERTABLE

adds or drops columns and constraints from a table, andmodifies data types of existing columns.

RENAMETABLE

changes the name of a table, replacing the old name with thenew name in the system catalogs.

DROPTABLE

deletes all data and indexes for a table and erases its entry inthe system catalogs.

CREATEVIEW

defines a table selected from rows and columns of existingtables and views. As the underlying tables change, so doesthe view built on them. See the section “Views” later in thischapter for more information about views.

DROPVIEW

deletes the definition of the view from the system catalogs,along with any views defined in terms of the one that isdropped. The underlying tables are unaffected.

CREATESYNONYM

defines an alternative name for a table or a view. For INFOR-MIX-4GL programs, the creator of the synonym is the userwho runs the program that creates the synonym.

Using SQL 3-11

Page 170: Manual Informix

Data Manipulation

DROPSYNONYM

deletes a synonym from the system catalogs.

RENAMECOLUMN

changes the name of a column, replacing the old name withthe new name in the system catalogs.

CREATEINDEX

creates an index on one or more columns of a table. See thesection “Indexing Strategy” later in this chapter for moreinformation on indexes.

ALTERINDEX

clusters a table in the order of an existing index or releasesan index from the cluster attribute.

DROPINDEX

deletes an existing index, removing it from the systemcatalogs.

UPDATESTATISTICS

updates the system catalogs by determining and insertingthe number of rows in the indicated tables. INFORMIX-4GLuses this information in optimizing queries but does notautomatically update the system catalogs after each INSERTor DELETE.

Data ManipulationThe data manipulation statements are the most frequently used SQLstatements:

DELETE deletes one or more rows from a table.

INSERT adds one or more rows to a table.

LOAD inserts rows from an operating system file.

SELECT retrieves data from one or more tables.

UNLOAD copies rows to an operating system file.

UPDATE 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 examplesillustrate its use:

SELECT lname, companyINTO p_lname, p_companyFROM customerWHERE customer_num = 101

3-12 Using SQL

Page 171: Manual Informix

Cursor Management

This statement queries the customer table and returns the single row forwhich the customer number is 101. From that row, it selects and places thevalues in the columns corresponding to the last name and company name ofthe contact in the program variables p_lname and p_company.

SELECT @quantity, @total_priceINTO quantity, total_priceFROM itemsWHERE order_num = 1001

This example shows another SELECT statement that returns a single row. Inthis example, the program variables quantity and total_price have the sameidentifier as the corresponding columns in the items table. There is no conflicthere, since the prefix @ distinguishes the column name from the programvariable.

A SELECT statement that returns a single row is called a singleton SELECTstatement and can stand alone. The section ‘‘Cursor Management’’ thatfollows describes how to handle SELECT statements that return more thanone row.

Cursor ManagementINFORMIX-4GL provides two functional types of cursors:

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

• An INSERT cursor, which you can use to insert rows into the database asa block.

The section ‘‘SELECT Cursors’’ describes how to associate a cursor with aSELECT statement and gives examples of the uses of the SELECT cursor. Thesection ‘‘INSERT Cursors’’ explains how to associate a cursor with an INSERTstatement and describes the advantages of using an INSERT cursor.

SELECT CursorsWhen a SELECT statement returns exactly one row, the values returned to theprogram variables are unambiguous. However, when more than one row canbe returned, it is necessary to have a device to distinguish one row fromanother. This device is called a cursor.

Using SQL 3-13

Page 172: Manual Informix

SELECT Cursors

The set of rows returned by a SELECT statement is called the active set for thestatement. Within an INFORMIX-4GL program, you can work with only onerow of the active set at a time. This row is called the current row, and it is ref-erenced by a cursor.

A cursor can be in one of two states: open or closed. When a SELECT cursoris in an open state, it is associated with an active set and can point to thecurrent 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 activeset, although it remains associated with the SELECT statement.

The following sections describe how to use the cursor managementstatements to process rows returned by a SELECT statement. (For completeinformation 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 aSELECT statement. In the DECLARE statement, you specify the type of cursorthat you want to use:

• A regular (or ‘‘non-scrolling’’) cursor allows rows to be retrieved from theactive set in consecutive order. You also DECLARE a regular cursor whenyou 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 ran-dom order.

• A regular or SCROLL cursor can be specified as WITH HOLD. Unlike reg-ular or SCROLL cursors that are not WITH HOLD, a cursor DECLAREd asWITH HOLD is not closed at the end of a transaction.

For example, the following DECLARE statement associates a SCROLL cursornamed q_curs with a SELECT statement that retrieves all the rows from thecustomer table:

DECLARE q_curs SCROLL CURSOR FORSELECT * FROM customer

The following DECLARE statement associates a non-scrolling cursor with aSELECT statement that retrieves customer rows based on a value that the usersupplies for column last name:

PROMPT "Enter a last name: " FOR last_name

DECLARE cust_curs CURSOR FORSELECT * FROM customerWHERE lname MATCHES last_name

3-14 Using SQL

Page 173: Manual Informix

SELECT Cursors

A cursor name has meaning only from the point at which it is DECLAREdto the end of the source-code file. The DECLARE statement for a cursor mustphysically appear before any statement that refers to it. For example, thefollowing program will not compile because the DECLARE statement forq_curs appears after the FOREACH statement that refers to it. (See thefollowing section, ‘‘Retrieving and Processing Rows’’ for more informationabout FOREACH.

DATABASE stores

MAINDEFINE 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 FOREACHEND MAIN

FUNCTION get_curs()DECLARE q_curs CURSOR FOR

SELECT * FROM customerEND FUNCTION

Retrieving and Processing Rows

Once you have DECLAREd a cursor for a SELECT statement, you can useeither the FOREACH statement or the OPEN, FETCH, and CLOSE statementsto retrieve and process the rows specified by the SELECT statement.

Using SQL 3-15

Page 174: Manual Informix

SELECT Cursors

The FOREACH Statement

Using the FOREACH statement, you can select rows and execute a seriesof statements for each row returned by a query. The following example usesa FOREACH statement to retrieve and display rows in the customer table:

PROMPT "Enter a last name: " FOR last_name

DECLARE q_curs CURSOR FORSELECT * 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 theactive set is exhausted:

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

• 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 rowsspecified 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 toexplicitly control the behavior of a cursor:

OPEN puts the cursor in an open state with regard to the SELECT state-ment. The OPEN statement causes the SELECT statement to runwith the current program variables and leaves the cursor pointingjust before the first row of the resulting active set. While the cursoris in an open state, subsequent changes to any program variablesthat appear in the SELECT statement associated with the cursor donot affect the active set.

FETCH advances the cursor to the specified row (either FIRST, LAST, NEXT,PRIOR or PREVIOUS, ABSOLUTE n, or RELATIVE m) and retrieves

3-16 Using SQL

Page 175: Manual Informix

SELECT Cursors

the values from that row. If a FETCH statement moves the cursorbefore the first row or after the last row, the error variable statushas the value NOTFOUND (= 100), as does the SQLCODE compo-nent of the SQLCA record. (See the section “SQLCA Record” laterin this chapter for more information.) NOTFOUND indicates thateither end of the active list has been reached.

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

For example, consider the following DECLARE statement:

DECLARE x CURSOR FORSELECT order_num, order_date

FROM ordersWHERE paid_date IS NULL

AND ship_date > p_dateFOR UPDATE OF paid_date

This statement names a cursor x and associates it with the SELECT statementthat follows the FOR keyword. The SELECT statement returns the order num-ber and order date for those unpaid orders whose shipping date was laterthan the date in the program variable p_date. The statement also enables afuture UPDATE statement to modify the paid_date column. The DECLAREstatement does not perform the query; it simply assigns the cursor to theSELECT statement.

OPEN x

When you execute the OPEN statement later in your program, the Booleanexpression in the WHERE clause of the SELECT statement uses the value of thevariable 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 tothe first row, and assigns to the program variables order_num andorder_date the values of the columns order_num and order_date in thefirst row:

UPDATE ordersSET paid_date = TODAY

WHERE CURRENT OF x

The UPDATE statement substitutes the current date (returned by the TODAYfunction) 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

Page 176: Manual Informix

SELECT Cursors

The cursor x is now put into a closed state, and the active set is effectively dis-solved. An immediate FETCH statement would be an error because a cursorin a closed state cannot point to anything. If, at a later time, you should exe-cute the statement

OPEN x

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

Deleting or Updating the Current Row

You can use special forms of the DECLARE, DELETE, and UPDATE statementsto delete or update the current row in an active set. You cannot use a SCROLLcursor to process the rows returned by a SELECT statement, and the SELECTstatement cannot include an ORDER BY clause.

To delete a row in an active set, you must include a FOR UPDATE clausein the DECLARE statement for a non-SCROLLing cursor, and also specifya WHERE CURRENT OF clause in a subsequent DELETE statement. Thefollowing program fragment is an example.

-- Prompt user, then read name from terminal.PROMPT "Enter a last name: "FOR last_name

DECLARE q_curs CURSOR FORSELECT * FROM customerWHERE lname MATCHES last_name

FOR UPDATE

FOREACH q_curs INTO cust_recIF status <> 0

EXIT FOREACH

-- 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 IFEND FOREACH. . .

3-18 Using SQL

Page 177: Manual Informix

SELECT Cursors

The cursor remains between rows after a DELETE WHERE CURRENT OF state-ment is executed. This means that you cannot refer to the cursor in anotherDELETE or UPDATE statement until you use a FETCH statement to advancethe cursor to the next row.

You can update the current row if you include a FOR UPDATE clause in theDECLARE statement for a non-SCROLLing cursor, and a WHERE CURRENT OFclause in a subsequent UPDATE statement. The following example allows theuser to update the address information in the current row:

DECLARE q_curs CURSOR FORSELECT * FROM customer

FOR UPDATE

FOREACH q_curs INTO cust_recIF 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 customerSET 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 IFEND FOREACH

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

Using SQL 3-19

Page 178: Manual Informix

SELECT Cursors

The following example allows the user to update the fname and lnamecolumns of the current row:

BEGIN WORK

DECLARE q_curs CURSOR FORSELECT * FROM customer

FOR UPDATE OF fname, lname

FOREACH q_curs INTO cust_recIF 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 customerSET fname = cust_rec.fname,

lname = cust_rec.lnameWHERE CURRENT OF q_curs

END IFEND FOREACH

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

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

The SCROLL Cursor

When you need to process the rows returned by a SELECT statement inrandom order, you must DECLARE a SCROLL cursor and use the OPEN,FETCH, and CLOSE statements.

3-20 Using SQL

Page 179: Manual Informix

SELECT Cursors

When you initially FETCH a row with a SCROLL cursor, all the rows in theactive set up to and including the FETCHed row are placed in a temporary fileand remain there until you close the cursor. If you then FETCH the same rowor any row prior to it, INFORMIX-4GL retrieves the row from the temporaryfile instead of from the database.

The temporary file allows you to retrieve rows in a random order. It alsomeans, however, that subsequent changes to the database may not bereflected in the active set used by a SCROLL cursor. Thus, you cannotDECLARE a SCROLL cursor FOR UPDATE. Instead, you must DECLARE FORUPDATE a regular cursor or a cursor WITH HOLD when you plan to performa subsequent UPDATE WHERE CURRENT OF or DELETE WHERE CURRENT OFaction.

The following example shows how to use a SCROLL cursor and variouscursor management statements to retrieve and display rows in the customertable.

MAIN. . .

DECLARE q_curs SCROLL CURSOR FORSELECT * FROM customer

WHERE lname MATCHES last_name

OPEN q_cursFETCH FIRST q_curs INTO p_customer.*

IF status = NOTFOUND THENCALL mess("No customers found.")

ELSEDISPLAY BY NAME p_customer.*CALL viewcust()

END IFCLOSE q_curs

. . .END MAIN

The MAIN program block includes the following statements:

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

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

• The FETCH FIRST statement attempts to retrieve the first row of theactive set.

Using SQL 3-21

Page 180: Manual Informix

SELECT Cursors

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

• The CLOSE statement releases the active set after all rows have beenprocessed.

The viewcust function displays a menu that lets the user view the rowsin 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 IFDISPLAY 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 IFDISPLAY 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 followingCOMMAND clauses:

Next includes a FETCH NEXT statement that attempts to retrieve thenext row of the active set. The IF statement returns the cursor tothe last row and displays a message if the value of the status vari-able indicates that the cursor has moved beyond the last row ofthe active set. The DISPLAY BY NAME statement displays on thescreen the row retrieved by the appropriate FETCH statement.

Previous includes a FETCH PREVIOUS statement that attempts to retrievethe previous row of the active set. The IF statement returns the cur-

3-22 Using SQL

Page 181: Manual Informix

SELECT Cursors

sor to the first row, and displays a message if the value of the sta-tus variable indicates that the cursor has moved beyond the firstrow of the active set. The DISPLAY BY NAME statement displayson the screen the row retrieved by the appropriate FETCHstatement.

First includes a FETCH FIRST statement that retrieves the first row in theactive set and displays it on the screen.

Last includes a FETCH LAST statement that retrieves the last row in theactive set and displays it on the screen.

Exit includes an EXIT MENU statement that terminates the MENUstatement.

All FETCH statements except the default FETCH NEXT statement require thatyou first DECLARE a SCROLL cursor. The default FETCH statement workswith all cursors.

Note: When you open a cursor that identifies a SELECT statement containing a pro-gram variable, INFORMIX-4GL runs the SELECT statement with the current valueof the program variable. In the following example, the active set produced by the firstOPEN statement differs from the active set produced by the second OPEN statementbecause the value of last_name changes from Baxter to Grant :

LET last_name = "Baxter"

DECLARE q_curs SCROLL CURSOR FORSELECT * 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 WORKoperations 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 transac-tion, and you must explicitly CLOSE the cursor.

Using SQL 3-23

Page 182: Manual Informix

SELECT Cursors

The following example outlines a typical program structure that uses a cur-sor WITH HOLD.

LET sel1 = "SELECT order_date FROM orders WHERE customer_nu m = ? FOR UPDATE"PREPARE st1 from sel1DECLARE 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 TRUEFETCH c_master INTO p_custnum

IF status = NOTFOUNDTHEN EXIT WHILE

END IF

BEGIN WORKOPEN c_detail USING p_custnum

WHILE trueFETCH c_detail INTO p_orddate

IF status = NOTFOUNDTHEN 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 WORKstatement appears after you OPEN the c_master cursor and perform aFETCH.

• The COMMIT WORK at the end of each iteration of the first WHILE loopdoes not close the c_master cursor. The cursor remains open to FETCH thenext master row after the COMMIT WORK has closed the c_detail cursorand released all locks. The updated rows are now available to other userson the system.

If you do not use a cursor WITH HOLD, you must place the BEGIN WORK andCOMMIT WORK statements completely outside the first WHILE loop. Youwould open both the c_master and c_detail cursors, FETCH all master rows,and FETCH and UPDATE all detail rows within the single transaction. Thisapproach has the following drawback: it holds all locks for the duration of theentire loop. If your program updates a large number of rows, you can

3-24 Using SQL

Page 183: Manual Informix

INSERT Cursors

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

Cursors WITH HOLD and Locks

In a non-MODE ANSI database with transactions, you must open any cursorDECLAREd FOR UPDATE (but not WITH HOLD) inside a transaction. (In aMODE ANSI database, all statements are automatically within a transaction.)Thus, any UPDATE or DELETE actions that are based on a cursor that is notDECLAREd as WITH HOLD occur within a transaction. You can always rollback the actions if necessary.

In a database that is not MODE ANSI, you cannot roll back an UPDATEor DELETE operation performed with a cursor WITH HOLD outside of atransaction, because an SQL operation that takes place outside a transactionis treated as a singleton transaction. Any locks acquired during a singletontransaction 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 doinga read-only, forward scan over a table, independent of transaction bound-aries. 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 discussionof 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 messagewhen the DBANSIWARN environment variable is set, or when the programis compiled with the -ansi flag.

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

Using SQL 3-25

Page 184: Manual Informix

INSERT Cursors

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

DECLARE associates a cursor with an INSERT statement. (The INSERTstatement cannot contain an embedded SELECT statement.)You cannot DECLARE a SCROLL INSERT cursor.

OPEN sets up an insert buffer for an INSERT cursor.

PUT stores a row in the INSERT buffer for later insertion into thedatabase. When you fill the buffer (by executing a series ofPUT statements), INFORMIX-4GL automatically inserts therows into the appropriate table as a block.

FLUSH forces INFORMIX-4GL to insert the buffered rows into thedatabase without closing the INSERT cursor. You can forcethe insertion using the FLUSH statement, but you cannot delayinsertion by not using the FLUSH statement.

CLOSE flushes the insert buffer and closes the INSERT cursor.

For databases with transactions, you must issue the OPEN, PUT, FLUSH, andCLOSE statements within a transaction.

For example, you can use these cursor management statements to insert cus-tomers into the customer table, block by block. See the following example:

DECLARE ins_curs CURSOR FORINSERT INTO customer VALUES (p_customer.*)

OPEN ins_curs

LET answer = "y"

WHILE answer = "y"

INPUT BY NAME p_customer.fnameTHRU 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

Page 185: Manual Informix

INSERT Cursors

This example includes the following statements:

• The DECLARE statement associates a cursor called ins_curs with anINSERT 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 enteredon a screen form into the customer table, block by block. Specifically, theINPUT statement allows the user to enter customer information on ascreen form and stores the information in the p_customer record. The PUTstatement stores the current values in the p_customer record in the insertbuffer. If the insert buffer becomes full as the result of a PUT statement, therows are automatically inserted into the customer table as a block.

• The CLOSE statement inserts any rows that remain in the insert buffer intothe customer table and closes the INSERT cursor.

When you use an INSERT cursor, you should CLOSE the cursor to insert anybuffered rows into the database before allowing your program to end. Theuser can lose data if the cursor is not closed properly. For example, if the userpresses the Interrupt key during input in the following program, INFOR-MIX-4GL closes the INSERT cursor before leaving the program. (Any remain-ing rows in the insert buffer are inserted into the database before the programstops.)

DEFER INTERRUPT. . .DECLARE ins_curs CURSOR FOR

INSERT INTO customer VALUES (p_customer.*)OPEN ins_cursLET answer = "y"WHILE answer = "y"

INPUT BY NAME p_customer.fname THRU p_customer.phoneON KEY (INTERRUPT)

CLOSE ins_cursEXIT PROGRAM

END INPUTLET p_customer.customer_num = 0PUT ins_cursPROMPT "Do you want to enter another customer (y/n) ? "

FOR answerEND WHILECLOSE ins_curs. . .

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

Using SQL 3-27

Page 186: Manual Informix

Dynamic Management

chapter, for more information on these variables.) If INFORMIX-4GL simplyputs a row in the insert buffer, it assigns the following values to these globalvariables:

status = 0SQLCA. SQLERRD [3] = 0

If INFORMIX-4GL successfully inserts a block of rows into the database as aresult of a PUT, FLUSH, or CLOSE statement, it assigns the following values:

status = 0SQLCA. SQLERRD [3] = the number of rows inserted

If, as a result of a PUT, FLUSH, or CLOSE statement, INFORMIX-4GL isunsuccessful in its attempt to insert an entire block of rows into the database,it assigns the following values:

status = a negative number correspondingto the error message

SQLCA. SQLERRD [3] = the number of rows successfully inserted

Dynamic ManagementThe preceding discussion assumes that you know what the SQL statementsare when you write your 4GL programs. That is the case for most applicationswhere you are performing predetermined activities on your database. Insome advanced applications, however, you will not know the statement atcompile time:

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

• Programs intended to work with different databases whose structure canvary

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 dynamicmanagement statements refer to the SQL statement throughthe statement identifier.

EXECUTE runs the previously PREPAREd statement associated withthe statement identifier. Use EXECUTE for all PREPAREdstatements except the following statements:

• SELECT statements

3-28 Using SQL

Page 187: Manual Informix

Preparing Statements

• INSERT statements that use an insert cursor

DECLARE has options that DECLARE a cursor for a PREPAREd SELECTor INSERT statement.

FREE releases the database engine resources that are required by aPREPAREd statement.

Preparing StatementsYou can use the PREPARE statement with either a character string or acharacter variable that evaluates to an SQL statement. The form of thePREPARE statement that you choose depends on the type of input (if any)required by the statement. You can use either form of the PREPARE statementif the statement requires no input or input for values. If the statement requiresinput for SQL identifiers such as column names, you must use the PREPAREstatement with a character variable.

In general, you can improve the performance of your programs byPREPARing statements that you plan to execute many times. Specifically,you might want to PREPARE a statement that requires different input eachtime it is executed.

Note: You can PREPARE any SQL statements except these:

CLOSE FETCH PREPAREDECLARE LOAD SELECT (with INTO variable clause)EXECUTE OPEN UNLOAD

See the section “SQL Statement Summary” earlier in this chapter for moreinformation about SQL statements. Chapter 2 describes the INFORMIX-4GLstatements which you cannot PREPARE.

Note: When you issue a DECLARE statement that includes the INSERT or SELECTkeywords, you declare a cursor that can perform an associated PUT or FETCH state-ment, even though you do not explicitly PREPARE the statement. For example,

DECLARE m_curs CURSOR FORINSERT INTO state VALUES (code, sname)

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

Using SQL 3-29

Page 188: Manual Informix

Preparing Statements

Statements That Require No Input

If a statement requires no input, you can PREPARE it from either a characterstring 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 statementrequires 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 avalue. Specifically, the question mark can represent a value or expression ina character string, but not an SQL identifier (such as a column name or tablename). Usually, you use a question mark to represent a value in the followingclauses:

• 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 zipcod e = ? WHERE CURRENT OF q_curs"

When you PREPARE a statement from a character string, you do not need tosupply values for the question marks until you execute the PREPAREd state-ment. (See the section “Executing PREPAREd Statements” later in this chap-ter for more information.)

3-30 Using SQL

Page 189: Manual Informix

Preparing Statements

Preparing a Character Variable

Alternatively, you can PREPARE a statement that requires input for valuesfrom a character variable.

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

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

The following example shows how to use this approach to PREPARE a state-ment that selects rows from the customer table based on a customer numberthat 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 con-catenates a character string containing part of the SELECT statement to thevariable cust_num, which contains a customer number that the user sup-plies. INFORMIX-4GL then assigns the resulting string to the large charactervariable sel_stmt and PREPAREs it.

When you use this approach, you must supply input values when you assignthe SQL statement to the character variable that you will later PREPARE.

Note: If you use the LET statement to concatenate strings to variables that containCHAR or DATE values, or DATETIME or INTERVAL constants, make sure thatquotes appear around those values in the resulting character string. To embed a quotein 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 isBaxter :

SELECT * FROM customer WHERE lname MATCHES "Baxter"

Using SQL 3-31

Page 190: Manual Informix

Preparing Statements

In contrast, the statements like the following do not require quotation marks aroundplaceholders for values:

DECLARE q_curs CURSOR FORSELECT * 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 thatrequires data for an SQL identifier (such as a column name, table name, user-name, view name, or synonym). The approach that you use is identical to thatdescribed in the previous section.

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

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

The following example shows how to use this approach to PREPARE astatement 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, itconcatenates a character string containing part of the GRANT statement tothe character variable p_user, which contains a username. INFORMIX-4GLthen assigns the resulting string to grant_stmt and PREPAREs it.

3-32 Using SQL

Page 191: Manual Informix

Executing PREPAREd Statements

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

• SELECT statements

• INSERT statements that require a cursor

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

The EXECUTE Statement

If you have PREPAREd a non-SELECT statement from a character variable orfrom a character string that does not contain question marks, you can run itwith a simple EXECUTE statement, as shown in the following examples:

PREPARE s1FROM "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 doescontain question marks, you must use the EXECUTE statement with a USINGclause. This clause consists of the USING keyword followed by one or moreprogram variables representing the values that replace the question marksin the PREPAREd character string.

Using SQL 3-33

Page 192: Manual Informix

Executing PREPAREd Statements

The EXECUTE statement in the following example executes a DELETEstatement using a customer number that the user supplies:

PREPARE s1FROM "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 statu s = 0 THENDISPLAY "Row deleted."

END IFIF 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 thisexample, it substitutes the current value of cust_num for the question markin the character string.

3-34 Using SQL

Page 193: Manual Informix

Executing PREPAREd Statements

Running PREPAREd SELECT Statements

If you PREPAREd a SELECT statement from a character variable or from acharacter string that does not contain question marks, you can use aDECLARE 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 doescontain one or more question marks, you must use the DECLARE statementwith an OPEN statement that includes a USING clause. As described

Using SQL 3-35

Page 194: Manual Informix

Executing PREPAREd Statements

previously, this clause consists of the USING keyword followed by one ormore program variables representing the values that replace the questionmarks 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 THENEXIT WHILE

END IF

DISPLAY BY NAME p_customer.*

. . .

END WHILE

CLOSE q_curs

When INFORMIX-4GL opens the cursor for the PREPAREd SELECT statementin this example, it substitutes the current value of zip for the question markin 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 subsequentDELETE or UPDATE statement to delete or update the current row. If youwant to use DECLARE FOR UPDATE with a PREPAREd SELECT statement,

3-36 Using SQL

Page 195: Manual Informix

Executing PREPAREd Statements

make sure that the FOR UPDATE clause appears as part of the PREPAREd char-acter 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 theEXECUTE statement or the PUT statement. A previous section, ‘‘The EXECUTEStatement,’’ describes how to use the EXECUTE statement if you want INFOR-MIX-4GL to insert one row into the database at a time. This section explainshow to DECLARE a cursor and use the PUT statement to insert rows into thedatabase through an insert buffer.

If you PREPARE an INSERT statement from a character variable or from acharacter string that does not contain question marks, you can use theDECLARE, OPEN, FLUSH and/or CLOSE statements with a simple PUTstatement, 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 doescontain 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

Page 196: Manual Informix

Preparing Multiple SQL Statements

clause. This clause consists of the FROM keyword, followed by one or moreprogram variables representing the values that replace the question marks inthe 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 substi-tutes the current value of p_customer.company for the question mark in thePREPAREd INSERT statement and stores the row in the insert buffer for laterinsertion into the database.

Preparing Multiple SQL StatementsINFORMIX-4GL supports PREPAREd objects that combine more than one datamanipulation statement. To use this dynamic management feature involvesthe same procedures as for simple PREPAREd statements, but with characterstrings that concatenate several SQL statements that you can successivelyexecute to perform some task. (A multiple-statement PREPARE cannot,however, reference an object like a table or synonym that is created byanother SQL statement that you specify in the same PREPARE statement.)

3-38 Using SQL

Page 197: Manual Informix

The FREE Statement

The following example updates the stores database by replacing the existingmanufacturer codes with new codes. Since the manu_code columns arepotential join columns that link three of the tables, the task of replacingthe old codes with the new must be performed in three tables.

DATABASE stores

MAINDEFINE 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_cod e = ? WHERE manu_code = ?;","UPDATE stock SET manu_cod e = ? WHERE manu_code = ?;","UPDATE items SET manu_cod e = ? WHERE manu_code = ?"

PREPARE exmulti FROM sqlmulti

EXECUTE exmultiUSING 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, anditems) as a single action.

The FREE StatementYou can create a PREPAREd statement explicitly in a PREPARE statement,which assigns an INFORMIX-4GL identifier to the statement that you specifyin the FROM clause. You can also create a PREPAREd statement implicitly, byassociating a cursor with a DECLARE statement that includes the SELECT orINSERT keywords. When you specify that cursor in an OPEN statement,INFORMIX-4GL automatically PREPAREs the associated INSERT or SELECTstatement.

Both explicitly and implicitly PREPAREd statements require database engineresources. You can ignore this cost in typical programs, but there is a limit tothe number of PREPAREd objects that the 4GL application can create.

Using SQL 3-39

Page 198: Manual Informix

Data Access

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

FREE statement-name

FREE cursor-name

Always use the first form if you explicitly PREPAREd the statement. Thesecond form is for implicitly PREPAREd statements to which you assignedno statement-name. If you assigned a statement-name with PREPARE, freeingan associated cursor does not release the PREPAREd statement.

After a successful FREE statement, you cannot use statement-name with acursor or with EXECUTE unless you PREPARE it again. If you FREE a cursor,you cannot use it again until you OPEN it.

Data AccessA user has access to the database, a table, and to specific columns within atable only when the DBA or the owner of the table specifically grants theseprivileges. You can temporarily limit access to a table by executing theLOCK TABLE statement. (Under transactions, the affected rows are lockeduntil the transaction is complete. Explicit table/record locking is generallynot required.) The following SQL statements affect data access:

GRANT grants database access privileges to specific users or to thepublic.

REVOKE removes database access privileges from specific users orfrom the public.

LOCKTABLE

limits access to the table to the current user only, or allowsother users only to read the table. Use the LOCK TABLE state-ment only when making major changes to a table in a multi-user environment and when simultaneous interaction withthe table by another user would interfere. LOCK TABLEdecreases the accessibility of the database, since it preventsother users from accessing the table. If the database hastransactions and is not MODE ANSI, you must issue a BEGINWORK statement before you can issue the LOCK TABLEstatement.

UNLOCKTABLE

restores access to a previously LOCKed table.

3-40 Using SQL

Page 199: Manual Informix

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 thesection “Locking” later in this chapter.

Chapter 7 identifies the various keywords that can specify user privilegesin the GRANT and REVOKE statements.

User Status and PrivilegesWhen you create a database, you are automatically the DBA of that databaseand are the only one who has access to the database. Another user does nothave access to a database until you grant the CONNECT privilege to that per-son. Another user cannot create or drop tables and indexes unless granted theRESOURCE privilege. Only the DBA (you, initially) can grant these privileges.You can also grant the DBA privilege to another user. The DBA privilegeextends all the powers of the Database Administrator to the grantee, includ-ing the ability to alter the system tables; to drop, start, and roll forward thedatabase; and to grant CONNECT, RESOURCE, and DBA privileges to others.

If you have the RESOURCE privilege, you have the CONNECT privilege bydefault. With the DBA privilege, you have both the RESOURCE and CONNECTprivileges. You can only revoke the privilege of a DBA grantee; you cannotrevoke your own DBA privilege. If you, as the creator of a database, grantDBA privileges to another user, that user can revoke the DBA privilege fromyou, the database creator. This last property permits the transfer of authorityfrom the maker of the database application to the person who has responsi-bility for maintaining the database.

INFORMIX-4GL allows the CONNECT and RESOURCE privileges to begranted TO PUBLIC, in addition to specifically named users.

In addition to these database-level privileges, the owner of the table can granta collection of table-level privileges . These privileges permit the granteeaccess to specific columns to execute SELECT or UPDATE statements, or givethe grantee authority to insert new rows, delete old rows, create indexes, andalter 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 defaulttable-level privileges are granted. You must explicitly grant these privileges.However, if you use START DATABASE to convert your database to MODEANSI, the existing privileges remain in effect unless you specifically revokethem.

Using SQL 3-41

Page 200: Manual Informix

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 specifiedtable or index. (You can give others the privilege of executing the ALTERTABLE, GRANT, and REVOKE statements, with certain restrictions.) Theowner of a table is the username of the person who executed the CREATETABLE statement. The owner of an index is the one who executed the CREATEINDEX statement. Execution occurs when the compiled INFORMIX-4GL pro-gram containing the CREATE statements is run, not when the INFORMIX-4GLprogram is compiled.

Data IntegrityINFORMIX-4GL has features to protect the integrity of your data. Thesefeatures include recovery procedures through transaction logs and audit trails,and concurrency control through record locking and table locking.

TransactionsINFORMIX-4GL supports data integrity by implementing the idea of transac-tions. A transaction is a series of database operations (SQL statements) thatyou want to be completed entirely or not at all. Examples of transactions areabundant in bookkeeping, where several operations on several differentaccounts must be made as a unit or the books will be out of balance. You canuse the following statements to control transactions in INFORMIX-4GLprograms:

BEGINWORK

marks the start of a transaction (if the database is notMODE ANSI).

COMMITWORK

marks the end of a transaction by authorizing all databasechanges since the transaction began.

ROLLBACKWORK

marks the end of a transaction by revoking all databasechanges since the transaction began.

STARTDATABASE

initiates a new transaction log file and (optionally)converts a database to MODE ANSI.

ROLLFORWARDDATABASE

uses a transaction log file to restore a database frombackup.

The BEGIN WORK, COMMIT WORK, ROLLBACK WORK, and ROLLFORWARDDATABASE statements are only available when the database has a transactionlog. You can use the WITH LOG IN clause of the CREATE DATABASE or STARTDATABASE statements to create a transaction log file that records all modifi-

3-42 Using SQL

Page 201: Manual Informix

Transactions

cations to the database. If you also specify the MODE ANSI option, transac-tions are implicit, and you are always within a transaction. You terminate thetransaction when you issue a COMMIT WORK or ROLLBACK WORKstatement.

In terms of transactions, there are three kinds of 4GL databases:

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

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

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

Databases Without Transactions

A database without transactions may require considerable recovery effort ifit becomes corrupted through failure of a data manipulation statement, par-ticularly if the error occurs within a series of closely related database opera-tions that form a single unit of work. For example, under transactions, youcan UPDATE several rows as a single unit of work. If the UPDATE fails afterchanging some of the rows but not all, you can ROLLBACK the transaction tothe original state where no rows are modified. Without transactions, youmust take explicit action to restore the updated rows. (The “Audit Trails” sec-tion later in this chapter describes a recovery procedure for databases with-out transactions.)

Databases with Implicit Transactions

If you want a database to have implicit transactions, you must create orstart the database as MODE ANSI and specify a transaction log file. All SQLstatements are automatically part of a transaction.

Note: You do not need to use the BEGIN WORK statement with a MODE ANSIdatabase, since the statement is implied.

Using SQL 3-43

Page 202: Manual Informix

Transactions

Databases with Explicit Transactions

If your database supports explicit transactions, you must issue theBEGIN WORK statement before you perform a series of operations that youwant to consider a unit. This statement causes all subsequently altered rowsof the database tables to be locked against modification by others (althoughothers can view them).

If you do not execute the BEGIN WORK statement, INFORMIX-4GL treats eachdata manipulation statement that changes the database as a singleton transac-tion. Each statement, if it executes successfully, is committed, and the data-base is permanently altered. If the statement fails, there is an automaticrollback to the status before the statement.

You must execute cursor manipulation statements inside a transaction if yourdatabase supports explicit transactions. That is, first execute the BEGINWORK statement before opening a cursor. All open cursors that are not WITHHOLD 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. Theactual limit depends on your operating system. Try to restrict the definitionof a transaction to a few statements that involve only a few rows. If youexpect that the number of rows to be entered during the transaction will belarge, LOCK the tables involved until the transaction is completed.

Regardless of whether a transaction is explicit or implicit, you can terminatethe transaction with a COMMIT WORK statement when you are satisfied thatthe series of operations has produced the desired results. If you are not satis-fied with the results, you can terminate the transaction with a ROLLBACKWORK statement. With the exceptions stated in the next paragraph, this state-ment restores the database to the state that existed immediately before thetransaction began. Both the COMMIT WORK and the ROLLBACK WORK state-ments release all row and table locks, making the data accessible for modifi-cation by others.

On INFORMIX-SE, you cannot roll back GRANT or REVOKE statements, norany of the data definition statements. These statements alter the number ornames of tables, or change the number, names, data types, or indexes of col-umns. If they were executed successfully, they are committed, and the ROLL-BACK WORK statement cannot undo them. If your database supports explicittransactions, you should not use these statements within a transaction.

3-44 Using SQL

Page 203: Manual Informix

Transaction Log File Maintenance

Transaction Log File MaintenanceThe transaction log file can become quite large and, periodically, the DBA willwant to archive it on tape and initiate another log file. At the same time, theDBA should also create a backup of your database. In general, every log filemust have a corresponding archive copy of the database. After backing upthe log file and the database, the DBA must specify an empty log file. To reusethe same log file, the DBA should create an empty log file with the same nameas 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 STARTDATABASE statement just before making a backup of the database. TheSTART DATABASE statement locks the database in EXCLUSIVE MODE while itis operating so that no further changes can be made. If START DATABASEfails, no database is open.

If the database is without transactions and you want to use transactions, theDBA must execute the START DATABASE command just before making a copyof the database.

If there is a backup copy of the database and a transaction log file that beginswith the operations executed immediately after the backup was made, theDBA can bring the backup database up to date with the ROLLFORWARDDATABASE statement. This statement recovers the database through the lastterminated transaction. The DBA must load the backup database files andexecute the ROLLFORWARD DATABASE statement. After rolling the databaseforward, the DBA is the only one who has access to the database, since it is leftin an exclusive mode. This state allows the DBA to check the database forerrors before making it generally available. Logging does not occur duringthis checking phase. The DBA must close the database when it has beenrestored correctly.

Audit TrailsAn 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 pur-pose similar to that of a transaction log: each is used to maintain a record ofmodifications to a database, and each can be used to update backup copies ofa database.

Three audit trail statements are available to protect the integrity of a table:

CREATE AUDIT creates an audit trail for a table.

DROP AUDIT removes the audit trail on a table.

Using SQL 3-45

Page 204: Manual Informix

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 beginwriting 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 audittrail file and pathname is the full pathname of the audit trail file. The audit trailfile should be on a physical device other than the one that holds the data sothat a system failure affecting the device that holds the data does not alsodamage 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 executeda CREATE AUDIT statement, but before you have made any changes to thetable. Once you have started the audit trail and have made a backup, you areready to work with the table.

You can drop and create an audit trail file whenever you want. Drop and cre-ate the audit trail files just before you make a complete backup of the devicecontaining the data file. If a system failure should occur, you can use the audittrail to back up the table from the time of the last backup to the time when thefailure occurred.

Recovering a Table

In the event of a system failure, you can use the RECOVER TABLE statementto restore a database table by using a backup copy of the table and an audittrail file. You must first restore a backup copy of the table. The backup copymust be in the original state that it was in when the audit trail was started. Ifit is not in the original state, the recovery fails. The format of the recoverystatement 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 thecontents of the audit trail file. Then run the CREATE AUDIT statement to starta new audit trail file. Finally, make a new backup copy of the table.

3-46 Using SQL

Page 205: Manual Informix

Comparison of Transactions and Audit Trails

Comparison of Transactions and Audit TrailsTransactions provide data integrity in two ways. First, they guarantee thatSQL statements are either successfully completed or completely canceled. If,for example, you update several rows of one or more tables within a transac-tion, 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 logto recover an entire database.

Audit trails are associated with individual tables. They do not guarantee thatmodifications to several rows of a table either succeed entirely or fail withoutany effect. You can use an audit trail file only to recover the table for which itis created.

You should consider using audit trails in place of a transaction log only whenyou have one or a few critical tables and you do not need the additional facil-ities provided by transactions. If you need to maintain the integrity of thedatabase as a whole, or need the guarantee that SQL statements are executedas a unit either entirely or not at all, you must use transactions.

LockingINFORMIX-4GL uses locking to prevent different users from executing con-flicting operations on the same data. Without locking, for example, two userscould 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 oneupdated by user A and the one updated by user B). Without some method ofconcurrency control, the user whose row is the last one actually written to thefile ‘‘wins’’ and overwrites changes by the other user.

The following SQL statements control locking:

LOCKTABLE

limits access to the table to the current user only or allows otherusers only to read the table. Use the LOCK TABLE statementonly when making major changes to a table in a multi-userenvironment, and when simultaneous interaction with thetable by another user would interfere. LOCK TABLE decreasesthe accessibility of the database since it prevents other usersfrom accessing the table. If the database has transactions but isnot MODE ANSI, you must issue a BEGIN WORK statementbefore you can issue the LOCK TABLE statement.

UNLOCKTABLE

restores access to a previously locked table.

Using SQL 3-47

Page 206: Manual Informix

Row-Level Locking

SET LOCKMODE

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

In addition, in the rare instance in which you need to limit access to the entiredatabase 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 strategycan differ slightly, depending on whether or not the database uses transactionmanagement. Data definition statements, such as ALTER TABLE, CREATEINDEX, and so on, use implied table-level locking. You can explicitly specifytable-level locking. The following sections describe each level of locking andthe methods for its use.

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

Row-Level LockingOrdinarily, INFORMIX-4GL locks a row when you execute an UPDATE state-ment, or when you execute a FETCH statement and the cursor is DECLAREdwith 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 samerow at the same time. One program receives the lock and can proceed withthe update. The other program either fails in its attempt or waits for that pro-gram to release the lock. (See the section “Wait for Locked Row” later in thischapter.)

If the UPDATE statement affects more than one row, INFORMIX-4GL uses thesame row-locking strategy. As soon as a row is UPDATEd, the lock is releasedand the next row is locked and UPDATEd. When the UPDATE finishes, allrows are unlocked.

If you want more control over the update of multiple rows, you can DECLAREa cursor FOR UPDATE. The WHERE clause of the SELECT statement specifiesthe 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 nextrow.

3-48 Using SQL

Page 207: Manual Informix

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 thetransaction. The end of a transaction is either a COMMIT WORK, where allmodifications are made to the database, or a ROLLBACK WORK, where noneof the modifications are made.

INFORMIX-4GL locks a row when it is selected for update. For example, ifyou DECLARE a cursor FOR UPDATE, the FETCH statement locks the row. Ifthe row is updated, it remains locked until the end of the transaction. If therow is not updated, the lock is released upon the next FETCH.

Table-Level LockingUse table-level locking to lock an entire table and prevent others fromaltering or seeing rows in that table.

You may want to use this form of locking, for example, during batch opera-tions that affect every row in a table. If the operations must be completed asa single transaction, it may be more efficient to lock the entire table beforebeginning the transaction. Normally, under transactions, INFORMIX-4GLlocks each row manipulated by an UPDATE, DELETE, or INSERT statement. Ifyou lock the entire table, however, INFORMIX-4GL does not use row-levellocking, because it is not necessary. As a result, you are not likely to reach thelimit that your operating system can place on the number of rows that can belocked at any one time. INFORMIX-4GL performs table-level locking auto-matically 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 datafrom the table, but they are not able to INSERT, DELETE, or UPDATE rowsin the table.

• If you lock the table IN EXCLUSIVE MODE, other users are not able toaccess the table at all until you execute an UNLOCK TABLE statement.

Because locking an entire table prevents others from adding or altering datain the table, use this feature sparingly. Lock the entire table only when row-level locking (as described in the previous section) is not sufficient.

Using SQL 3-49

Page 208: Manual Informix

Wait for Locked Row

Wait for Locked RowIf another user locks a row in a table at the row level and you attempt to alteror delete that row (or examine it with SELECT statement FOR UPDATE),INFORMIX-4GL returns an error, stating that the row is locked. If you preferthat INFORMIX-4GL wait on any locked row until the competing processunlocks it, you can execute the SET LOCK MODE TO WAIT statement. Fromthen 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 kernellocking.

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

Indexing StrategyThere are two major purposes for creating an index on columns of a databasetable: to speed sorting of rows and to optimize the performance of queries.When your application writes reports involving complex queries through alarge database, significant time savings can result from judicious indexing.The drawback to having an index is that indexes slow down the process ofinserting new data into the database. When you update a table, its indexescan also be modified. This is not a problem when you are adding informationinteractively, a row at a time, but can become serious when it is necessary toinsert a large number of rows from one table into another.

The solution to this potential conflict between needs is to take a dynamicapproach to indexing. One of the advantages of an Informix relational data-base is that you do not have to decide issues like which columns to index atthe time that you create your tables. You should write your applications tocreate indexes when you need them and to drop them when they get in theway. It takes time to create an index on a table already containing data, andyou should create only those indexes that optimize the queries you make. Forexample, by judicious scheduling, you can create your indexes in anticipa-tion of batch report writing during the night and drop them the next morningbefore there are huge data-entry needs.

3-50 Using SQL

Page 209: Manual Informix

Indexing Strategy

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

• Do not create indexes for small tables with fewer than 200 rows. Speedthat you gain from using an index does not overcome the time requiredto 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/noresponses, or zip codes in a small city. Because data like this producesskewed indexes, indexing can cause the optimizing strategy of INFOR-MIX-4GL to fail and queries to take longer than if the columns were notindexed. If you have a frequent need to have data sorted on columns witha small range of possible values, create a temporary table of the sorteddata. Another approach is to redesign the database with separate tablesfor each alternative value.

• If the WHERE clause of a SELECT statement imposes a condition on a sin-gle column, put an index on that column. If conditions are placed onseveral columns, make a composite index on all the affected columns. Forthe SELECT statement

SELECT * FROM items WHERE order_num > 1015

put an index on order_num. For the statement

SELECT * FROM itemsWHERE 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 betweena single column in one table and a single column in another table, createan index on the column in the table with the larger number of rows. If sev-eral columns of one table have join conditions with several columns inanother table, create a composite index on the affected columns of thetable with the larger number of rows. For the SELECT statement

SELECT * FROM items, stockWHERE items.stock_num = stock.stock_num

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

Using SQL 3-51

Page 210: Manual Informix

Query Optimizer

statement before the SELECT statement so that INFORMIX-4GL knows thecurrent size of the tables.

For the statement

SELECT * FROM items, stockWHERE 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 OptimizerIt is not always easy to know how indexes are used during a query, but youcan determine this by issuing the SET EXPLAIN statement. When you set thisstatement 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 thedatabase engine to improve performance, is written into this file for each sub-sequent query. The recorded information includes the order of table access,how filters are applied, and what (if any) indexes are used in processing thequery.

For example, if your queries seem to be taking longer than necessary, youmay 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 addedor dropped. The SET EXPLAIN statement provides you with information todetermine exactly how the database is being accessed and to help you assesswhether changing indexes may improve the decisions of the optimizer.

Auto-IndexingIf you execute a SELECT statement that includes a join between two tables andthere are no indexes on the joined columns, INFORMIX-4GL creates a tempo-rary index on the table with the larger number of rows before performing thejoin. The index disappears when the query finishes. This enhancementis transparent to the user, except for a dramatic improvement in the speedof unindexed joins.

Clustered IndexesSince UNIX systems extract information from the disk in blocks, rows physi-cally on the same block and already in the order of an index are retrievedmore quickly. Ordinarily, no relationship need exist between the physical

3-52 Using SQL

Page 211: Manual Informix

NULL Values

order of the data in the .dat file and the order in an index. You can, at leasttemporarily, make the physical order in the table the same as the order in anindex through clustering.

INFORMIX-4GL orders, or clusters, the physical data in a table when youcreate a new index by executing a variant of the CREATE INDEX statementor 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 updatethe information in existing rows, a table that you cluster according to anindex does not stay that way. Over time, you can expect the benefit of anearlier clustering to disappear and you may want to cluster the table againusing an ALTER INDEX TO CLUSTER statement.

Since a table can have only one physical order, you can have only one clus-tered index on a table at any given time. You can change the physical orderto reflect a different index by executing two ALTER INDEX statements:

1. Execute an ALTER INDEX TO NOT CLUSTER statement to release the clus-ter attribute from the first index.

2. Execute an ALTER INDEX TO CLUSTER statement to attach the clusterattribute to the second index.

You cannot execute the ALTER INDEX or CREATE INDEX statements on aview.

NULL ValuesThe basic purpose of introducing NULL values in a database is to indicatewhen no value has been assigned to a particular column in a particular rowof a table. Your reasons for not having assigned a value could include notknowing the correct value, or that no value yet exists. The NULL can alsoindicate that no value is appropriate for a given column because of the valuesthat were entered into other columns.

As an example, consider entering data for a bank customer who is requestinga loan. If the customer, Mr. Farthing, is not employed, the employer columnin the client table will have no entry for this customer. This CHAR columnwill have the value NULL. The hire_date column is meaningless ifMr. Farthing is not employed. There is no appropriate date to enter; the valueis NULL.

Using SQL 3-53

Page 212: Manual Informix

Default Values

Default ValuesIn INFORMIX-4GL, the default value for a column is NULL. INFORMIX-4GLmakes a distinction for number values between zero and NULL, and for char-acter values between blanks and NULL. You do not need to know howINFORMIX-4GL implements the value NULL to make use of it.

By definition, type SERIAL columns can never contain the NULL value. Col-umns 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 theNOT NULL clause in the CREATE TABLE statement. INFORMIX-4GL will pre-vent 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 statementwhen you add a new column. The reason is that INFORMIX-4GL enters aNULL value into that column for all rows that already exist.

A column for which you create a unique index can have, at most, one NULLvalue.

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 Version1 database, INFORMIX-4GL enters a blank for type CHAR columns, zeros for num-ber columns, and a very large negative value for type DATE columns. Since zerocould well be an acceptable value for a number column (for example, the value for atype 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 ofthe dbupdate utility describes how you can avoid using NULL values.)

The NULL in ExpressionsIf any value that participates in an arithmetic expression is NULL, the valueof the entire expression is NULL. For example, consider the following query:

SELECT order_num, ship_charge/ship_weightFROM ordersWHERE order_num = 1023

If ship_weight is NULL because the order with number 1023 is new and theshipping charge has not yet been determined, the value returned forship_charge/ship_weight will also be NULL.

3-54 Using SQL

Page 213: Manual Informix

The NULL in Boolean Expressions

The situation is different when you use one of the aggregate functions. (SeeChapter 7 for a description of the aggregate functions.) COUNT(*) counts allrows, even if the value of every column in the row is NULL. COUNT(DISTINCT column-name), AVG, SUM, MAX, and MIN ignore rows with NULLvalues for the column in their argument and return the appropriate valuebased on the rest of the rows. If, however, a column contains only NULL val-ues, then COUNT (DISTINCT column-name) returns zero, and the other fouraggregate functions return NULL for that column.

The NULL in Boolean ExpressionsTo incorporate NULL values into Boolean expressions, it is necessary toenlarge the number of truth values from simply TRUE and FALSE to includeUNKNOWN. If one of the expressions of a Boolean expression is NULL, the truthvalue of the Boolean expression is UNKNOWN. For example, the Booleanexpression,

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 toTRUE, F to FALSE, and ? to UNKNOWN).

Figure 3-1 Combining Boolean Expressions

The NULL in WHERE ClausesIf the Boolean expression in a WHERE clause evaluates to UNKNOWN for a par-ticular row, INFORMIX-4GL treats the search condition as not satisfied anddoes not select or modify that row.

Consider this clause

WHERE ship_charge/ship_weight < 5AND order_num = 1023

AND T F ? OR T F ? NOT

T T F ? T T T T T FF F F F F T F ? F T? ? F ? ? T ? ? ? ?

Using SQL 3-55

Page 214: Manual Informix

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 thetruth 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 theentire search condition is UNKNOWN. Consequently, that row will not be cho-sen. If the search condition had used an OR in place of the AND, the searchcondition would be TRUE.

You can select (or reject) rows containing NULL values with a new type ofsearch condition:

column IS [ NOT ] NULL

You must use the keyword IS. It is not permitted to write the condition asfollows:

column = NULL (Incorrect)column != NULL (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 isNULL. In particular, no row will be returned if both column1 and column2are NULL. This is merely a special case of the more general rule that Booleanexpressions containing NULL values have an UNKNOWN truth value.

Similarly, if a subquery returns a single NULL value, the search conditionevaluates to UNKNOWN.

The NULL in ORDER BY ClausesFor the purpose of sorting rows using the ORDER BY clause, the NULL valueis treated as being less than a non-NULL value. When the ordering is ascend-ing ( ASC ), the NULL values come first; when the ordering is descending( DESC ), the NULL values come last.

The NULL in GROUP BY ClausesWhen you refer to a column in a GROUP BY clause, INFORMIX-4GL treats allrows containing a NULL value in the column as a single group. NULL valuesare considered identical when evaluated within a GROUP BY clause.

3-56 Using SQL

Page 215: Manual Informix

The NULL Keyword in INSERT and UPDATE Statements

The NULL Keyword in INSERT and UPDATE StatementsWhen you execute the INSERT statement, INFORMIX-4GL will insert theNULL value into all columns for which you do not provide a value, or forall columns not listed explicitly. Since the value-list of the INSERT statementmust be the same length as the column-list, you can use the keyword NULLto 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. Simi-larly, you can use the NULL keyword to modify a column value when usingthe UPDATE statement. For a customer whose previous address required twoaddress lines, but now requires only one, you would use the following entry:

UPDATE customerSET address1 = "123 New Street",

address2 = NULL,city = "Palo Alto",zipcode = "94303"

WHERE customer_num = 134

ViewsViews are constructs on a database that allow you to do the following tasks:

• Provide different users with different windows (called ‘‘views’’) on thedata in the database. A single view can involve columns from differenttables, or can show values that are functions of the values from the col-umns. A view has a name and looks to a user as if it were a table. The usercan query a view, for example, using the same syntax as though the viewwere a table in the database.

• Limit access to sensitive data by allowing users to see only aggregateinformation. With the GRANT and REVOKE statements, you can prevent auser from seeing any salary data in a personnel table. With a view, youcan allow the user to see average salaries in various groups, but still pro-tect the individual salary data.

• Permit users to update, insert, and to delete data in the database asthough the data were organized as it appears in a view. You can alsoexamine through a view the changes made in a real table of the database.

Using SQL 3-57

Page 216: Manual Informix

Creating and Deleting Views

Views are therefore dynamic windows into the database and are not staticsnapshots. They differ in this respect from a temporary table created by theINTO TEMP clause of a SELECT statement or the CREATE TEMP TABLE state-ment. Such temporary tables show you only the state of the database whenthe temporary table was created.

Although views appear to be tables in the database, they differ in severalimportant ways. You cannot create an index on a view. Under certain condi-tions, you cannot update or modify the data perceived through a view. Anobvious case occurs when the ‘‘column’’ seen in a view is really an expressiongenerated from actual database tables. Generally speaking, there is no wayto determine the appropriate change in the underlying columns involvedin 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 thedatabase through views, how to modify the database through a view, andhow to set up privileges for a view.

Creating and Deleting ViewsYou must use the CREATE VIEW statement to create a view. (See Chapter 7 forcomplete information about the CREATE VIEW statement.) A view is deter-mined 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 7for the definition of the UNION operator.) The SELECT statement is stored inthe sysviews system catalog. When you subsequently refer to a view inanother statement, INFORMIX-4GL performs the defining SELECT statementin executing the new statement.

You can use the same column names as in the underlying table for the viewor you can assign new names. When a column in a view is the evaluation ofan expression or is not unique (because, for example, you have included allthe columns of a join, including the columns that define the join), you mustsupply new names. These column names are stored in syscolumns with thecolumn names of regular tables.

You can delete a view by executing the DROP VIEW statement. When youdrop a view, you also drop all views that were defined in terms of that view.

Querying Through ViewsYou can make queries involving views exactly as though they were tables inthe database. If possible, 4GL first combines the view-defining SELECT state-ment with the query to create a new SELECT statement and then executes the

3-58 Using SQL

Page 217: Manual Informix

Modifying Through Views

new statement. Otherwise, it creates the view as a temporary table andapplies the query to the table. 4GL can detect errors during either of thesephases.

Modifying Through ViewsIn addition to querying through views, you can use the INSERT, UPDATE, andDELETE statements with views. INFORMIX-4GL combines the view-definingSELECT statement with the view-referring statement and then executes it. Thefollowing restrictions apply when modifying tables through a view:

• You cannot modify the database through a view if the view definitioninvolves joins, the GROUP BY clause, the DISTINCT keyword, or an aggre-gate function. If any of these features appears in the view definition, thecreator of the view cannot execute INSERT, DELETE, or UPDATE state-ments on the view. You can define a view, however, using a subquery thatrefers to another table. This approach can often circumvent the restrictionon joins. (See the section “Data Constraints Using Views,” later in thischapter.)

• A view column can be UPDATEd only if it is derived directly from a data-base table and not as a result of an expression. Expression-derivedcolumns are called ‘‘virtual’’ columns. You cannot INSERT rows througha view that contains virtual columns, although you can DELETE a row thatcontains a virtual column.

• You cannot execute the ALTER TABLE, CREATE INDEX, ALTER INDEX, orUPDATE STATISTICS statements on a view. You do, however, receive thebenefit of existing indexes on the underlying tables.

You can use an INSERT statement on a view that shows only a portion of anunderlying table. When you do so, the unmentioned columns of the under-lying table will receive NULL values. If one of the unmentioned columns doesnot permit NULL values, INFORMIX-4GL will not permit you to INSERT to theview.

If you drop a column from a table underlying a view and you have definedthe view in terms of that column, INFORMIX-4GL issues an error if you sub-sequently refer to the view (other than with the DROP VIEW statement).

Unless you create the view with a WITH CHECK OPTION clause, it is possibleto INSERT or UPDATE data through a view that does not satisfy the limita-tions on the view. A row inserted or updated in this manner is no longeraccessible through the view. For example, a view could be created that allowsthe user access only to customers from Palo Alto. If, when using the view, theuser creates a new row with a customer from Menlo Park, the user cannot

Using SQL 3-59

Page 218: Manual Informix

Privileges with Views

select the row through the view. If the city column on an existing row isupdated to Menlo Park , the row disappears from the view. The WITHCHECK OPTION clause in the CREATE VIEW statement causes INFORMIX-4GLto 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 cancontain duplicate rows. Duplicate rows can occur in a view even if theunderlying table has unique rows. If a view is defined on the items tableand contains only the columns order_num and total_price, the view containsduplicate rows if two items from the same order have the same total price. Ifyou put the cursor on one of the rows where total_price = $1234.56 andupdate the total_price to $1250.00 through the view, you have no way ofknowing which item you have increased.

Privileges with ViewsWhen you create a view, you receive the same privileges that you had on theunderlying tables. If you have these privileges with the GRANT OPTION, youcan 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 SELECTprivilege, since multi-table views do not permit you to INSERT, DELETE, orUPDATE. You must have the SELECT privilege on all of the columns fromwhich a multi-table view is derived to have the SELECT privilege on the entireview. If, as a result of these restrictions, you have no privileges on a view, theCREATE VIEW statement returns an error code.

Data Constraints Using ViewsThe purpose of data constraints is to ensure that all data entered into thedatabase satisfies pre-assigned limitations. Through a form in INFOR-MIX-4GL, data entry can be controlled with the INCLUDE attribute that listsvalues and ranges of values permitted for a column. The values entered intothe syscolval table in the include column serve a similar purpose. (SeeChapter 4.) In both of these cases, however, the list of allowed values is staticand is dependent only on the designated column.

It is often desirable to define allowed value ranges dynamically, based on thevalues in other columns or even in other tables. The existence of views and,specifically, the WITH CHECK OPTION clause permits the DBA to control theentry of data into the database. This is most easily demonstrated with anexample taken from the stores database.

3-60 Using SQL

Page 219: Manual Informix

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 ASSELECT * FROM items

WHERE total_price < 20000 ANDEXISTS (SELECT stock_num, manu_code

FROM stockWHERE stock.stock_num

= items.stock_numAND 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 WHEREclause. Because of the dynamic nature of views, the view will only containrows corresponding to current stock items if you change the stock table byadding rows corresponding to new stock items or deleting old ones. Byextending the WHERE clause, this example can be expanded to cover verygeneral data-constraint needs.

Outer JoinsAn outer join between two tables treats the two tables unsymmetrically. Oneof the tables is dominant (often referred to as ‘‘preserved’’), and the othertable is subservient. If the subservient table has no rows satisfying the joincondition, the outer join attaches a row of NULL values to the row of the dom-inant table before projecting the desired columns. To illustrate, let a be a col-umn from tab1 and b a column in tab2. Further, let the values in the twotables be as shown in the following display:

tab1.a tab2.b2 43 25 6

5

Using SQL 3-61

Page 220: Manual Informix

Table Access by ROWID

INFORMIX-4GL syntax requires that the subservient table in an outer join bepreceded by the keyword OUTER in the FROM clause. The following SELECTstatement contains an outer join between tab1 (the dominant table) and tab2(the subservient table):

SELECT a, bFROM tab1, OUTER tab2WHERE a = b

The resulting table has the following three rows:

a b2 23 -5 5

Every value for a is present, and only those values for b that correspond to avalue in a are present. When there is no value in column b that satisfies thejoin condition, a NULL value (shown here as -) is substituted.

A WHERE clause is required in the case of outer joins and must set a conditionbetween the two tables.

See Appendix G for more information about outer joins.

Table Access by ROWIDYou can use the keyword ROWID in INFORMIX-4GL statements to refer to theinternal record number associated with a row in a database table. The ROWIDcan 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, youcan use the syntax

SELECT ROWID , * FROM table

to get the ROWID value for each row. You can also determine the ROWID ofthe 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 inter-nal record number. This feature is useful when there is no other unique col-umn 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 sequentialvalues of ROWID.

3-62 Using SQL

Page 221: Manual Informix

SQLCA Record

SQLCA RecordProper database management requires that all logical sequences of state-ments that modify the database continue successfully to completion. If, forexample, you UPDATE a customer account to show a reduction of $100 in thepayable balance and the next step, to UPDATE the cash balance, fails for somereason, your books will be out of balance. It is prudent to check that everySQL statement executes as you anticipated.

INFORMIX-4GL provides two ways to do this: the global variable status thatindicates errors both from form-related statements and SQL statements; anda global record SQLCA that allows you to test the success of SQL statements.The status variable provides the primary information, and SQLCA providesadditional information.

INFORMIX-4GL returns a result code into the SQLCA record after executingevery SQL statement except DECLARE. This record is shown here:

DEFINE SQLCA RECORDSQLCODE INTEGER,SQLERRM CHAR(71),SQLERRP CHAR(8),SQLERRD ARRAY [6] OF INTEGER ,SQLAWARN CHAR (8)

END RECORD

SQLCODE indicates the result of executing an SQL statement. It is set tozero for a successful execution of most statements and to NOT-FOUND ( = 100 ) for a successfully executed query that returnszero rows or for a FETCH that seeks beyond the end of an activeset.

SQLCODE is negative for an unsuccessful execution.

INFORMIX-4GL sets the global variable status equal to SQL-CODE after each SQL statement. See “Error Messages” after theappendixes for the error codes.

SQLERRM is not used at this time.

SQLERRP is not used at this time.

SQLERRD an array of six variables of type INTEGER

SQLERRD[1] is not used at this time.

SQLERRD[2] is the SERIAL value returned or ISAM errorcode.

SQLERRD[3] is the number of rows processed.

SQLERRD[4] is the estimated CPU cost for query.

Using SQL 3-63

Page 222: Manual Informix

SQLCA Record

SQLERRD[5] is the offset of error into the SQL statement.

SQLERRD[6] is the ROWID of last row.

SQLAWARN is a character string of length eight whose individual characterssignal various warning conditions (as opposed to errors) fol-lowing the execution of an SQL statement. The characters areblank if no problems were detected.

SQLAWARN[1] is set to W if one or more of the other warningcharacters has been set to W. If SQLAWARN[1]is blank, you do not have to check the remain-ing warning characters.

SQLAWARN[2] is set to W if one or more data items was trun-cated to fit into a CHAR program variable, or ifa DATABASE statement selected a databasewith transactions.

SQLAWARN[3] is set to W if an aggregate function ( SUM, AVG,MAX, or MIN ) encountered a NULL value in itsevaluation, or if a DATABASE statementselected a MODE ANSI database.

SQLAWARN[4] is set to W if a DATABASE statement selected anINFORMIX-OnLine database, or when thenumber of items in the select-list of a SELECTclause is not the same as the number of pro-gram variables in the INTO clause. The numberof values returned by INFORMIX-4GL is thesmaller of these two numbers.

SQLAWARN[5] is set to W if float-to-decimal conversion isused.

SQLAWARN[6] is set to W when your program executes anINFORMIX-4GL extension to ANSI standardsyntax, and the DBANSIWARN environmentvariable is set.

SQLAWARN[7] is not used at present.

SQLAWARN[8] is not used at present.

3-64 Using SQL

Page 223: Manual Informix

TODAY, CURRENT, and USER Functions

TODAY, CURRENT, and USER FunctionsINFORMIX-4GL provides functions to allow you to include the date, the dateand 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 con-stant 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 notUSER) in 4GL statements.

For example, if you wish to retrieve the rows that you have inserted into atable, you must define a CHAR column to contain the USER name. When youinsert 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 discussionon using the SELECT statement to return multiple rows.)

Use the TODAY function in the same way. You can insert the system date intoa 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 fromthe beginning of 1989 to the current instant.

SELECT * FROM table WHERE dt_colBETWEEN "1989-1-1 00:00:00" AND CURRENT

See the section “Built-in Functions” in Chapter 2 for more information aboutthe TODAY and CURRENT functions.

Using SQL 3-65

Page 224: Manual Informix

TODAY, CURRENT, and USER Functions

3-66 Using SQL

Page 225: Manual Informix

Chapter

4

Form Buildingand CompilingChapter Overview 3

Structure of a Form Specification File 4DATABASE Section 7SCREEN Section 9

Textual Information 11Display Fields 11Graphics Characters in Forms 13

TABLES Section 15ATTRIBUTES Section 17

Fields Linked to Database Columns 18Form-Only Fields 19Multiple-Line Fields 21Multiple-Column Fields 22Attributes Syntax 23

AUTONEXT 24COLOR 26COMMENTS 28DEFAULT 30DISPLAY LIKE 32DOWNSHIFT 33FORMAT 34INCLUDE 36NOENTRY 38PICTURE 39REQUIRED 41REVERSE 43UPSHIFT 44VALIDATE LIKE 46VERIFY 47

Page 226: Manual Informix

WORDWRAP 48INSTRUCTIONS Section 52

Field Delimiters 53Screen Records 55Screen Arrays 56

Default Screen Attributes 57The upscol Tables in a MODE ANSI Database 60

Creating and Compiling a Form 61Through the Programmer’s Environment 62Through the Operating System 63Using PERFORM Forms in INFORMIX-4GL 64

4-2 Form Building and Compiling

Page 227: Manual Informix

Chapter OverviewA screen form is a terminal screen display that can support input or outputtasks within a 4GL application program. You can use screen forms inconjunction with screen interaction and data manipulation statementsof INFORMIX-4GL to enter, retrieve, modify, or delete data.

Before you can use a customized screen form in your INFORMIX-4GL pro-gram, you must create a form specification file and use FORM4GL to compilethis file. The form specification file is an ASCII file that contains the screen for-mat and the instructions to INFORMIX-4GL about how to display the data.

The first and longest section of this chapter, “Structure of a Form Specifica-tion File,” describes the function and syntax of each of the required andoptional components of a 4GL form specification file. Another part of thischapter, “Default Screen Attributes,” describes the syscolval and syscolatttables into which you can insert default attributes, formats, and values forscreen fields of 4GL applications.

The section “Creating and Compiling a Form” describes how to useFORM4GL to compile form files for use in INFORMIX-4GL programs. The lastsection, “Using PERFORM Forms in INFORMIX-4GL” describes what hap-pens when an INFORMIX-4GL program uses screen forms designed for PER-FORM, the screen transaction program of INFORMIX-SQL.

Note: The FORM4GL syntax for forms that you design to work with INFOR-MIX-4GL is different in several significant ways from the syntax of PERFORM. Youcan use PERFORM forms with INFORMIX-4GL, but you must recompile themusing FORM4GL. In addition, not all of the PERFORM features are operative.

Form Building and Compiling 4-3

Page 228: Manual Informix

Structure of a Form Specification File

Structure of a Form Specification FileAn INFORMIX-4GL form specification file consists of three required sections(DATABASE, SCREEN, and ATTRIBUTES) and can also include two optionalsections (TABLES and INSTRUCTIONS). If present, these sections must appearin the following order:

• DATABASE Section: Each form specification file must begin with aDATABASE section identifying the database (if any) on which you want tobase the form.

• SCREEN Section: The SCREEN section appears next, showing the exactlayout of the form as you want it to appear on the screen. You must spec-ify the position of the screen fields for data entry and display, and anyadditional text or graphic characters.

• TABLES Section: A TABLES section must follow the SCREEN section if youdefine any field with the name of a column in a database table. TheTABLES section identifies all the tables whose columns are associatedwith screen fields in the ATTRIBUTES or INSTRUCTIONS sections, anddefines aliases for any table names or synonyms that require an ownerqualifier.

• ATTRIBUTES Section: The ATTRIBUTES section describes each field onthe 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 canspecify non-default field delimiters and can define screen records andscreen arrays.

Each section must begin with the keyword for which it is named. After youcreate a form specification file, you use the FORM4GL utility to compile it.Your INFORMIX-4GL application can then use program variables to transferinformation between a database and the fields of the screen form, as is illus-trated by the examples that appear in Chapters 7, 11, 12, and 13 of theINFORMIX-4GL User Guide.

4-4 Form Building and Compiling

Page 229: Manual Informix

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 ] ]

ATTRIBUTESfield-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 thismanual. The following are literal characters to be entered in your file, ratherthan 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 listedpreviously, and describe their syntax in detail.

Form Building and Compiling 4-5

Page 230: Manual Informix

Structure of a Form Specification File

ExampleFigure 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 ] Date Paid: [o22 ]

}

TABLEScustomer orders items manufact

ATTRIBUTESc1 = customer.customer_num

= orders.customer_num;...

c10 = customer.phone, PICTURE = " ###- ### - #### x##### ";...

o20 = orders.po_num;o21 = orders.ship_date;o22 = orders.paid_date;

INSTRUCTIONSSCREEN RECORD sc_order[5] (orders.order_date THRU orders.paid_date)

Figure 4-1 Sections of a Form Specification File

In this example, the screen form will display columns from several tables inthe stores database. The file is for a default physical screen size (24 lines of 80characters) and includes all five of the required and optional sections that aredescribed in the pages that follow.

This example is incomplete, since it omits portions of the SCREEN andATTRIBUTES sections that describe some of the screen fields. The ellipsisnotation ( . . . ) in those sections is a typographic device to simplify thisillustration.

4-6 Form Building and Compiling

Page 231: Manual Informix

DATABASE Section

DATABASE Section

OverviewThe DATABASE section of a form specification file identifies the database (ifany) 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. TheDATABASE section has this structure.

SyntaxDATABASE

{ database-name | FORMONLY } [WITHOUT NULL INPUT]

ExplanationDATABASE is a required keyword to mark the beginning of the

DATABASE section of a form specification file.

database-name is the name of a database that contains columns used todefine display fields of the form.

WITHOUTNULL INPUT

are keywords to indicate that database-name does not supportNULL values.

FORMONLY is a keyword to indicate that the screen form is not associ-ated with any database.

Notes1. You should use the WITHOUT NULL INPUT option only if you have

elected to create and work with a database that does not have NULLvalues. (See the description of dbupdate in Appendix E for the otherrequired steps.) For fields that have no other defaults, this option causesINFORMIX-4GL to display zeros as default values for number andINTERVAL fields, and blanks for character fields. The default DATE valueis 12/31/1899 , and the default for DATETIME is1899-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 TABLESsection of the form specification file. Use the table name formonly inthe ATTRIBUTES section in naming fields that are not linked to specificcolumns of a database.

Form Building and Compiling 4-7

Page 232: Manual Informix

DATABASE Section

ExamplesThe following DATABASE section specifies that any columns referenced inthe TABLES section are in the stores demonstration database:

databasestores

The next example of a DATABASE section specifies that the screen form is notassociated with any database:

databaseformonly

4-8 Form Building and Compiling

Page 233: Manual Informix

SCREEN Section

SCREEN Section

OverviewThe SCREEN section of the form specification file specifies the vertical andhorizontal dimensions of the physical screen, and the position of displayfields and other information that will appear on the screen form. This sectionis required. It has the following syntax:

SyntaxSCREEN [ SIZE lines [ BY cols ] ]{

screen-layout}[ END ]

ExplanationSCREEN is a required keyword to mark the beginning of the SCREEN

section.

SIZE is an optional keyword to specify the vertical and horizontaldimensions of the terminal screen.

lines is an integer that specifies the total number of lines ofcharacters (measured vertically) that the terminal screen candisplay. The default is 24 lines.

BY is an optional keyword to specify how many characters(measured horizontally) a line can display.

cols is an integer that specifies the width of the screen. Thedefault is the maximum number of characters in any line ofthe screen-layout.

{screen-layout}

is the group of display fields and optional text and graphicscharacters that define a screen form. The braces ( { } ) arerequired symbols to indicate the beginning and end of thescreen-layout, and do not represent a choice among requiredoptions.

END is an optional keyword to mark the end of the SCREENsection.

Form Building and Compiling 4-9

Page 234: Manual Informix

SCREEN Section

Notes1. 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, asdescribed near the end of this chapter, these SIZE defaults appearexplicitly in the file.

2. Your form4gl command line can override either or both of the linesor 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 thesystem, so no more than ( lines - 4 ) can display data.

4. If ( lines - 4 ) is less than the number of lines in the screen-layout, FORM4GLsplits your form into a new page after every (lines - 4) lines. INFOR-MIX-4GL does not support multiple-page forms, so any lines beyond thefirst page will overlay the last line of the first page if your screen-layout istoo large for your screen. (Create several form specification files if youneed to display more data than can fit on one form.)

5. If the SIZE clause or command line specify dimensions too small for thescreen-layout, FORM4GL issues a compile-time warning, but still producesthe compiled form that your file specified.

6. The screen-layout must be enclosed in braces ( { } ). It consists of displayfields and (optionally) textual information and graphics characters. Displayfields must be indicated by brackets ( [ ] ) that define the field length andthe position within a line of the form, and by field tag labels within thefield.

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 isnot required, but it is recognized by FORM4GL to provide compatibilitywith earlier Informix products.

4-10 Form Building and Compiling

Page 235: Manual Informix

SCREEN Section

ExampleThis figure schematically illustrates the structure of a SCREEN section. Herethe SCREEN SIZE dimensions specify a physical screen that can display up to35 lines of data, with up to 80 characters in each line. (Four of the 39 linesspecified here are reserved for the system.)

SCREEN SIZE 39 BY 80{

.

.

.Text, display fields, and graphic characters Screen layout

.

.

.}

[ END ]

Textual Information

A screen layout can specify strings of ASCII characters that appear on thescreen form. These characters can label the form and its fields, or otherwiseimprove the display. Except for the displacements described later in ‘‘Graph-ics Characters in Forms,’’ position in the screen layout determines where textappears on the screen. Text cannot overlap display fields, but the PICTUREattribute (described in “Attributes Syntax” later in this chapter) can specifyliteral 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 anassociated field tag to identify the field.

Syntax

[fieldtag ]

Explanation

[ ] are delimiters for a field. The width of the field is the number ofcharacters that can be placed between the brackets. (The bracketsare required in this context, and do not signify an optional syntax.)

fieldtag is the field tag that labels the display field.

Form Building and Compiling 4-11

Page 236: Manual Informix

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 includeletters, numbers, and underscores ( _ ).

3. Field tags are labels; they are not the same as field names. TheATTRIBUTES section links each field tag to a field name.

4. The same field tag can be used at more than one position in the SCREENsection of the form specification, if you want the same information toappear 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 describedlater 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 caninclude no more than 26 single-character fields.)

7. In a default form specification file, the widths of all fields are determinedby the data type of the corresponding columns in the database tables.(See “Creating and Compiling a Form” for more information aboutdefault form specification files.)

8. If you create your own form, you normally should set the width of eachdisplay field in the SCREEN section to be equal to the width of the pro-gram variable or column to which it corresponds.

9. Fields corresponding to number columns should be large enough tocontain the largest number that you might display. If the field is too smallto display an assigned number, INFORMIX-4GL fills the field withasterisks ( * ) to indicate the overflow.

10. Fields intended to display character data can be shorter than the definedcolumn length. INFORMIX-4GL fills a field from the left, and truncatesfrom the right any character string that is longer than the field to which itis assigned. Through subscripting, you can assign portions of a charactercolumn to one or more fields. (See the “ATTRIBUTES Section” later in thischapter.)

11. If you edit and modify the default form specification file or create a newfile, you can verify that the field widths match the width requirements ofthe corresponding CHAR columns by using the -v option of FORM4GL. Atthe system prompt, enter:

form4gl -v form-name

FORM4GL reports any discrepancies in the file form-name.err.

4-12 Form Building and Compiling

Page 237: Manual Informix

SCREEN Section

12. The “INSTRUCTIONS Section” later in this chapter describes an optionaldelimiter that can be used to separate consecutive display fields in ascreen layout.

Example

The SCREEN section listed below appears in the orderform.per form specifi-cation file in the INFORMIX-4GL demonstration application. This usesdefault screen dimensions (24 by 80). Notice the use of textual information forfield labels, a screen title, and ornamental lines. (The “INSTRUCTIONS Sec-tion” later in this chapter describes how repeated field tags are used in formsthat define screen arrays.)

Graphics Characters in Forms

You can include graphics characters in the SCREEN section to place boxes andother rectangular shapes in a screen form. Use the following characters toindicate the borders of one or more boxes on the form:

Symbol Purposep Use p to mark the upper-left corner.q Use q to mark the upper-right corner.b Use b to mark the lower-left corner.d Use d to mark the lower-right corner.- Use hyphens ( - ) to indicate horizontal line segments.| Use vertical ( | ) bars to indicate vertical line segments.

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

Form Building and Compiling 4-13

Page 238: Manual Informix

SCREEN Section

The meanings of these six special characters are derived from the gb or acscspecifications in the termcap or terminfo files, respectively. INFORMIX-4GLsubstitutes the corresponding graphics characters when you display thecompiled form.

Once the form has the desired configuration, use the \g string to indicatewhen 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 repre-sents a graphics character. To leave graphics mode, insert the string \g afterthe p, q, d, b, hyphen, or vertical bar.

Do not insert a \g string into original white space of a screen layout. Thebackslash should displace the first graphics character in the line, and pushthe remaining characters to the right. The process of indicating graphics dis-torts the appearance of a screen layout in the SCREEN section, compared tothe corresponding display of the screen form.

You can include other graphics characters in a form specification file. Themeaning, however, of a character other than the p, q, d, b, hyphen, andvertical bar is terminal-dependent.

To use graphics characters, the system termcap or terminfo files must includeentries for the following variables:

termcap:

gs the escape sequence for entering graphics mode.

ge the escape sequence for leaving graphics mode.

gb the concatenated, ordered list of ASCII equivalents for the sixgraphics characters used to draw the border.

terminfo:

smacs the escape sequence for entering graphics mode.

rmacs the escape sequence for leaving graphics mode.

acsc the concatenated, ordered list of ASCII equivalents for the sixgraphics characters used to draw the border.

See Appendix I, “Modifying termcap and terminfo,” and the manual thatcomes with your terminal for information about making changes to your ter-mcap or terminfo files to support these graphics characters.

4-14 Form Building and Compiling

Page 239: Manual Informix

TABLES Section

TABLES Section

OverviewThe third section of the form specification file lists all the tables that youreference elsewhere in the screen form. You do not need to display in thescreen form every column of every table listed, but any table or view whosecolumns are referenced in the form must be included.

In a MODE ANSI database, a form must qualify any table name with the ownerprefix 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 sectionto reference the table in other sections of the form specification file. Thestructure of the TABLES section is shown below:

SyntaxTABLES

[tab-alias = [ owner.] ] table . . .[ END ]

ExplanationTABLES is a keyword to begin the TABLES section.

tab-alias is the table alias in the form specification file.

owner is the username of whoever created tabname.

table is the identifier or synonym of table in its database.

END is an optional keyword to end the TABLES section.

Notes1. If the DATABASE section specifies FORMONLY, no TABLES section is

needed unless you give a field the VALIDATE LIKE or DISPLAY LIKEattribute in the ATTRIBUTES section, or type a field LIKE a databasecolumn.

2. Every table listed in the TABLES section must be part of the database thatyou specify in the DATABASE section.

3. Every database column referenced in the ATTRIBUTES section must bepart of some table specified in the TABLES section.

Form Building and Compiling 4-15

Page 240: Manual Informix

TABLES Section

4. The table identifier is the name listed in the tabname column of the systa-bles 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 didnot create table.

5. Except to assign a tab-alias in the TABLES section, a form file cannot qual-ify table with an owner prefix. You must define a tab-alias to reference theowner 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 theform specification file can reference screen fields as column or as table.column, but they cannot specify owner. table. column. You cannot specifytable. 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 limiton the number of tables and views in a form is machine-dependent.

8. The END keyword is not required.

ExamplesThe 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 = refdpt.booktabtab2 = athdpt.balltab

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

4-16 Form Building and Compiling

Page 241: Manual Informix

ATTRIBUTES Section

ATTRIBUTES Section

OverviewThe ATTRIBUTES section associates an identifier and a data type with everyfield in the SCREEN section. You can also describe the behavior and appear-ance of each field by using attributes to describe how INFORMIX-4GL shoulddisplay 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 thesection“Attributes Syntax.”

SyntaxATTRIBUTES

field-tag = field-description ;. . .

[ END ]

ExplanationATTRIBUTES is a required keyword to mark the beginning of the

ATTRIBUTES section.

field-tag is a field tag specified in the SCREEN section.

field-description specifies a field name and optional attributes.

END is an optional keyword to mark the end of the ATTRIBUTESsection.

Notes1. 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 inthe default screen records. (See the “INSTRUCTIONS Section” for moreinformation 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

Page 242: Manual Informix

ATTRIBUTES Section

Fields Linked to Database Columns

You can specify two kinds of field descriptions: those that associate a field tagwith the data type and default display attributes of a database column, andthose that link field tags to form-only fields.

Unless a screen field is form-only, its field-description must specify the identi-fier of some column in the database as the name of the field. Screen fields areassociated with database columns only during the compilation of the formspecification file. During the compilation process, FORM4GL examines twooptional tables, syscolval and syscolatt, for default values of the attributesthat you have associated with any columns of the database. (See the section“Default Screen Attributes” later in this chapter for a discussion of thesetables.)

After FORM4GL extracts these default attributes and identifies the data typesfrom the system catalogs, the association between the fields and databasecolumns is broken. INFORMIX-4GL programs must mediate between screenfields and database columns with program variables.

Syntax

field-tag = [ table.] column [ , attr-list ] ;

Explanationfield-tag is a field tag that identifies a field in the SCREEN section.

table is a table name or alias from the TABLES section.

column is the name of a column in table or, if you omit table, in some tablelisted in the TABLES section. This name can also appear in 4GLstatements that reference the field.

attr-list is one or more FORM4GL field attribute specifications, separatedby commas.

Notes

1. Although you must include an ATTRIBUTES section that names everyfield-tag, you are not required to specify any attributes.

2. You need to specify table only if column occurs in more than one table ofthe TABLES section. FORM4GL issues an error during compilation if thereis ambiguity. Because you can refer to field names collectively througha screen record built upon all the fields related to a single table, yourforms may be easier to work with if you specify table for each field.

4-18 Form Building and Compiling

Page 243: Manual Informix

ATTRIBUTES Section

(The ‘‘INSTRUCTIONS Section’’ provides more information about screenrecords.)

3. A screen field can display a portion of a character string by using sub-scripts in the column specification. Subscripts are comma-separatedintegers in square ( [ ] ) brackets to indicate starting and ending characterpositions within a string value.

Examples

The ATTRIBUTES section in the following file lists fields linked to columns inthe customer table. The UPSHIFT and PICTURE attributes listed here aredescribed later in this chapter.

DATABASE stores

SCREEN{

Customer Name:[f000 ][f001 ]Address:[f002 ][f003 ]

City:[f004 ] State:[a0] Zip Code:[f005 ]Telephone:[f006 ]

}

TABLES customer

ATTRIBUTESf000 = customer.fname;f001 = customer.lname;f002 = customer.address1;f003 = customer.address2;f004 = customer.city;a0 = customer.state, UPSHIFT;f005 = customer.zipcodef006 = customer.phone, PICTURE = " ###- ### - #### XXXXX";

Form-Only Fields

Form-only fields are not associated with columns of any database. They canbe used to enter or display the values of program variables. If the DATABASEsection specifies FORMONLY, this is the only kind of field description that youcan 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

Page 244: Manual Informix

ATTRIBUTES Section

Explanation

field-tag is the field tag used in the SCREEN section.

FORMONLY is a keyword indicating that the field does not correspondto a column of a table in the database.

field-name is an SQL identifier for the name of the field.

TYPE is a keyword to specify an INFORMIX-4GL data type.

data-type is any one of the INFORMIX-4GL data types except SERIAL.(See the section “Database Data Types” in Chapter 3 fordefinitions of the data types.)

LIKE is a keyword to associate the screen field with the data typespecification of a database column.

table is a table alias, name, or synonym.

column is the name of a column in the database.

NOT NULL are keywords to specify that, if you reference this field in anINFORMIX-4GL INPUT or INPUT ARRAY statement, the usermust enter a value in the field.

attr-list is a list of one or more FORM4GL display field attribute spec-ifications, separated by commas. (See the section “AttributesSyntax” for a list of FORM4GL attributes.)

Notes

1. You must specify a data-type only if you use the INCLUDE or DEFAULTattribute for this field. Otherwise, FORM4GL assumes the field is a CHARtype whose length is the width of the field. INFORMIX-4GL performs thenecessary data conversion for the corresponding program variable dur-ing 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 inthe SCREEN section.

3. If you specify one or more FORMONLY fields, INFORMIX-4GL behaves asif they formed a database table named formonly, with the field names ascolumn names.

4. When the DATABASE section has the WITHOUT NULL INPUT clause, theNOT NULL keyword instructs INFORMIX-4GL to use zero (number types)or blanks (character types) as a default value for this field in INPUT orINPUT ARRAY statements. If you do not specify any type, INFORMIX-4GLtreats the field as type CHAR.

4-20 Form Building and Compiling

Page 245: Manual Informix

ATTRIBUTES Section

;

Examples

The following form-only fields could be used in an order entry form to dis-play information about items:

f020 = formonly.manu_name;f021 = formonly.description;f022 = formonly.unit_price;f023 = formonly.unit_descr;f024 = formonly.order_placed

TYPE DATETIME YEAR TO HOUR NOT NULL, DEFAULT = CURRENT

The demonstration application uses the following form-only field to store therunning 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 mul-tiple-line field, repeat the same field tag in different fields of the layout in theSCREEN section, typically on successive lines. You must also specify theWORDWRAP attribute for that field tag in the ATTRIBUTES section. Duringinput and display, INFORMIX-4GL treats these fields as segments of a singlefield.

The following example shows only the SCREEN and ATTRIBUTES sections ofa form specification file that specifies a multiple-line field:

SCREEN SIZE 24 BY 80{

title: [title ]author: [author ]

synopsis: [synopsis ][synopsis ][synopsis ][synopsis ][synopsis ]

}. . .

ATTRIBUTEStitle = booktab.title;author = booktab.author;synopsis = booktab.synopsis, WORDWRAP COMPRESS;

Since the screen field whose tag is synopsis appears in five physical segmentsin the screen layout and has the WORDWRAP attribute, it is a multiple-linefield. 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 thecolumn, so it can display all of the text. Users of your 4GL application pro-

Form Building and Compiling 4-21

Page 246: Manual Informix

ATTRIBUTES Section

gram may expect all segments to be the same size and laid out in verticalalignment, as in the example, but that is not required. Segments can be ofdifferent sizes, and distributed over the screen in any arrangement.

In the description of the field in the last line of the ATTRIBUTES section, thekeyword WORDWRAP enables a multiple-line editor. If you omit it, wordscannot flow from segment to segment of the field, and users must move thecursor from field to field with Arrow keys or the RETURN key to edit valuesin the form. (See the description of the WORDWRAP attribute later in thischapter for more information about the multiline editor and about theCOMPRESS keyword.)

Multiple-Column Fields

A screen form that contains information from several database tables caninclude screen fields that display data via program variables from two ormore database columns.

The database columns that you assign to the same field must have the samefield size. Usually they also have the same data type. If they are charactercolumns, they must have the same length. The following specification in theATTRIBUTES section assigns two column names to a field tag, so that thenames 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 youassign several columns to the same field. The placement of attributes deter-mines when they take effect. When INFORMIX-4GL executes an INPUT,INPUT ARRAY, DISPLAY, or DISPLAY ARRAY statement, the screen fieldslisted (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 asemicolon ( ; ) 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 effec-tive only when table2.column is active. (The FORMAT and REVERSE attributes,described later in this chapter, always take effect if you include them in thedescription of a multiple-column field, regardless of their placement.)

4-22 Form Building and Compiling

Page 247: Manual Informix

ATTRIBUTES Section

Attributes Syntax

FORM4GL recognizes the following display field attributes:

AUTONEXT NOENTRYCOLOR PICTURECOMMENTS REQUIREDDEFAULT REVERSEDISPLAY LIKE UPSHIFTDOWNSHIFT VALIDATE LIKEFORMAT VERIFYINCLUDE WORDWRAP [ COMPRESS ]

Syntax for assigning each of these attributes is described in the sections thatfollow. For simplicity and clarity, these descriptions of the attributes that youcan 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 ortable.column is the name of a screen field (either linked to a database columnor FORMONLY ), and attr specifies an attribute. This format is simplified byignoring multiple-column fields, and by omitting terms that specify thedata-type and NOT NULL keywords of a form-only field. Here is the completesyntax 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 mul-tiple-column field.

Note: INFORMIX-OnLine supports an additional attribute, PROGRAM. Refer tothe INFORMIX-OnLine Programmer’s Manual for more information.

Form Building and Compiling 4-23

Page 248: Manual Informix

AUTONEXT

AUTONEXT

OverviewUse the AUTONEXT attribute to cause the cursor to advance automaticallyduring input to the next field when the current field is full.

Syntaxfield-tag = [ table. ] column, AUTONEXT;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

AUTONEXT is a keyword that tells INFORMIX-4GL to advance the cursorto the next field when the current field is full.

Notes1. You specify the order of fields in each INPUT or INPUT ARRAY statement.

2. AUTONEXT is particularly useful with character fields in which the inputdata are of a standard length, such as numeric postal codes, or the abbre-viations in the state table. It is also useful if a character field has a lengthof one, since only one keystroke is required to enter the data and to moveto the next field.

3. If data entered in the field does not meet requirements of other attributeslike INCLUDE or PICTURE, the cursor does not automatically move to thenext 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

Page 249: Manual Informix

AUTONEXT

ExampleThe demonstration application uses the customer form to enter all the namesand addresses of the customers. The following excerpt from the ATTRIBUTESsection 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 fillingthe field), the cursor moves automatically to the beginning of the next field(the customer.zipcode field). When five characters are entered into thecustomer.zipcode field (filling this field), the cursor moves automaticallyto the beginning of the next field (the customer.phone field).

Form Building and Compiling 4-25

Page 250: Manual Informix

COLOR

COLOR

OverviewYou can use the COLOR attribute to display field text in color on color moni-tors, or to specify other video attributes for field text.

Syntaxfield-tag = [ table. ] column, COLOR = dispmode [ . . . ] [ WHERE condition ] ;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a database columnor FORMONLY).

COLOR = is a keyword, followed by an equal ( = ) sign.

dispmode is the name of a screen color or intensity.

WHERE is a keyword to specify a Boolean expression.

condition is a Boolean expression. If it is TRUE, text in the field isdisplayed with the dispmode attribute.

Notes1. The condition can be a Boolean expression of the following forms:

expr relop expr expr [ NOT ] IN (expr [ , expr . . . ] )expr IS [ NOT ] NULL expr [ NOT ] BETWEEN expr AND expr( bool-expr ) expr [ NOT ] LIKE expr [ ESCAPE "char"]NOT bool-expr expr [ NOT ] MATCHES expr [ ESCAPE "char"]

bool-expr [ AND | OR ] bool-exprfor relop a relational operator ( = <> != > >= <= < ); bool-expr a Bool-ean expression; and expr the current field-tag, a constant, or TODAY orCURRENT, arithmetic symbols, or the unary minus symbol:

( expr ) expr { + | - | * | / } expr - expr2. 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 yourdispmode list applies to the field.

4-26 Form Building and Compiling

Page 251: Manual Informix

COLOR

4. If condition is FALSE, the field is displayed with default characteristics,rather than with the attribute specified by dispmode. (See “Default ScreenAttributes” later in this chapter.)

5. The dispmode list can specify zero or one color name, and zero or moreintensity names from these lists:

Color Text Display Intensity Text DisplayWHITE White BLINK BlinkingYELLOW Yellow * UNDERLINE UnderlinedMAGENTA Magenta * REVERSE Reverse (inverse) videoRED Red LEFT Left-justifiedCYAN CyanGREEN GreenBLUE Blue * The only attributes available on systemsBLACK Black where INFORMIXTERM = terminfo

ExamplesThis 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 = manufact.manu_code, color = red WHERE f002 = "HRO";f003 = customer.lname, color = red WHERE f003 LIKE "Quinn";f004 = mytab.col6, color = green WHERE f004 < 10000;f005 = mytab.col9, color = blue reverse WHERE f005 IS NULL,

color = yellow WHERE f005 BETWEEN 5000 and 10000,color = red blink WHERE f005 > 10000;

Related AttributeREVERSE

Form Building and Compiling 4-27

Page 252: Manual Informix

COMMENTS

COMMENTS

OverviewYou can use the COMMENTS attribute to cause INFORMIX-4GL to display amessage on the Comment line at the bottom of the screen. The message isdisplayed when the cursor moves to the associated field and is erased whenthe cursor moves to another field.

Syntaxfield-tag = [ table. ] column, COMMENTS = "message" ;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

COMMENTS = is a keyword, followed by an equal ( = ) sign.

message is a character string enclosed in quotation marks.

Notes1. 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 canreset this position with the OPTIONS statement.

3. The default position of the Comment line in a window is LAST. Youcan reset this position in the OPTIONS statement (if you want the newposition in all windows) or in the ATTRIBUTE clause of the appropriateOPEN WINDOW statement (if you want the new position in a specificwindow). See Chapter 7 for a description of the OPTIONS and OPENWINDOW statements of INFORMIX-4GL.

4. The most common application of the COMMENTS attribute is to giveinformation or instructions to the user. This is particularly appropriatewhen the field accepts only a limited set of values. (See the descriptionof the INCLUDE attribute later in this section for details of how to specifya range or a list of acceptable values for data entry.)

4-28 Form Building and Compiling

Page 253: Manual Informix

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 theCOMMENTS attribute in a field description unless the message isappropriate to all of the tasks in which the message can appear.

If the same field requires a different message for various tasks, youshould specify each message using the INFORMIX-4GL MESSAGE orDISPLAY statements, rather than in the form specification file.

ExampleThis field description specifies a message for the Comment line. The messagewill appear when the screen cursor enters the field that displays the firstname of a customer:

c2 = customer.fname, comments ="Please enter initial if available.";

Related AttributeINCLUDE

Form Building and Compiling 4-29

Page 254: Manual Informix

DEFAULT

DEFAULT

OverviewUse the DEFAULT attribute to assign a default value to a display field.

Syntaxfield-tag = [ table. ] column, DEFAULT = value;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

DEFAULT = is a keyword, followed by an equal ( = ) sign.

value is the default value.

Notes1. Default values have no effect when you execute the INPUT statement

using the WITHOUT DEFAULTS option. In this case, INFORMIX-4GL dis-plays the values in the program variables list on the screen. The situationis the same for the INPUT ARRAY statement, except that INFORMIX-4GLdisplays the default values when you insert a new row.

2. If you use the WITHOUT NULL INPUT option in the DATABASE sectionand you do not use the DEFAULT attribute, then character fields defaultto 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 valueis 1899-12-31 23:59:59.99999 .

3. If you do not use the WITHOUT NULL INPUT option in the DATABASEsection, all fields default to NULL values unless you use the DEFAULTattribute.

4. If table is FORMONLY, you must specify a data type when you assign theDEFAULT attribute to a field. (See the syntax in the section “Form-OnlyFields” earlier in this chapter.)

5. For CHAR or DATE fields, enclose value in quotes ( " ).

4-30 Form Building and Compiling

Page 255: Manual Informix

DEFAULT

6. If the field type is DATETIME or INTERVAL, you can enclose value in quo-tation ( " ) 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 thesequoted and literal formats, a value of data type INTERVAL can also bespecified in the format:

expression UNITS field

Here expression can be a literal number, or the name of a number columnor variable, or an expression in parentheses that evaluates to a number.UNITS is a keyword, and field is a DATETIME element name, such asMONTH, DAY, HOUR, and so forth. (Here field is neither a field name norfield tag.)

7. If both the DEFAULT attribute and the REQUIRED attribute are assigned tothe same field, the REQUIRED attribute is ignored.

8. Use the TODAY keyword as the value to assign the current date as thedefault value of a DATE field.

9. Use the CURRENT keyword as the value to assign the current date andtime as the default for a DATETIME field.

ExampleThe 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

Page 256: Manual Informix

DISPLAY LIKE

DISPLAY LIKE

OverviewUse the DISPLAY LIKE attribute to display the field by using the attributesassigned to a database column in the syscolatt table.

Syntaxfield-tag = [ table. ] column, DISPLAY LIKE tbl.col;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

DISPLAY LIKE are required keywords.

tbl.col is the name of a database column.

Notes1. This attribute is equivalent to listing all the attributes that you have

assigned to tbl.col in the syscolatt table. See the section “Default ScreenAttributes” for details of the syscolatt table.

2. You do not need the DISPLAY LIKE attribute if table.column is the sameas tbl.col.

3. Do not use a column of type DATETIME or INTERVAL for tbl.col.

Examples12 = formonly.total, DISPLAY LIKE items.total_price;

Related AttributeVALIDATE LIKE

4-32 Form Building and Compiling

Page 257: Manual Informix

DOWNSHIFT

DOWNSHIFT

OverviewAssign the DOWNSHIFT attribute to a character field when you want INFOR-MIX-4GL to convert uppercase letters entered by the user to lowercase letters,both on the screen and in the corresponding program variable.

Syntaxfield-tag = [ table. ] column, DOWNSHIFT;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

DOWNSHIFT is the keyword that instructs INFORMIX-4GL to convertcharacter input data to lowercase letters in the programvariable.

NoteBecause uppercase and lowercase letters have different ASCII values, storingcharacter strings in one or the other format can simplify sorting and queryinga database.

Related AttributeUPSHIFT

Form Building and Compiling 4-33

Page 258: Manual Informix

FORMAT

FORMAT

OverviewUse the FORMAT attribute with a DECIMAL, SMALLFLOAT, FLOAT, or DATEfield to control the format of output displays.

Syntaxfield-tag = [ table. ] column, FORMAT = " format-string" ;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

FORMAT = is a keyword, followed by an equal ( = ) sign.

format-string is a string of characters to specify a data format. You mustenclose format-string in quotation marks.

Notes1. For DECIMAL, SMALLFLOAT, or FLOAT data types, the format-string

consists of pound signs (#) that represent digits, and a decimal point. Forexample, "###.##" produces at least three places to the left of the decimalpoint and exactly two to the right.

2. If the actual number displayed is shorter than the format-string, INFOR-MIX-4GL right justifies it and pads the left with blanks.

3. If the format-string is smaller than the display width, FORM4GL gives awarning, but the form is usable. INFORMIX-4GL displays the data rightjustified in the field.

4. If necessary to satisfy the format, INFORMIX-4GL rounds numbers beforedisplaying them.

5. For DATE data types, INFORMIX-4GL recognizes the following symbolsas special in the format-string:

mm produces the two-digit representation of the month.

mmm produces a three-letter abbreviation of the month; for exam-ple, Jan , Feb , and so on.

4-34 Form Building and Compiling

Page 259: Manual Informix

FORMAT

dd produces the two-digit representation of the day.

ddd produces a three-letter abbreviation of the day of the week;for example, Mon, Tue , and so on.

yy produces the two-digit representation of the year.

yyyy produces a four-digit year.

For dates, FORM4GL interprets any other characters as literals anddisplays them wherever you place them within format-string.

6. If FORMAT is an attribute of any field name of a multiple-column field, thefield uses the specified format-string regardless of which column is active.

ExamplesFor DATE fields:

Input Resultno FORMAT attribute 09/15/1989FORMAT = "mm/dd/yy" 09/15/89FORMAT = "mmm dd, yyyy" Sep 15, 1989FORMAT = "yymmdd" 890915FORMAT = "dd-mm-yy" 15-09-89FORMAT = "(ddd.) mmm. dd, yyyy" (Sat.) Sep. 15, 1989

Related AttributePICTURE

Form Building and Compiling 4-35

Page 260: Manual Informix

INCLUDE

INCLUDE

OverviewUse the INCLUDE attribute to specify acceptable values for a field, and tocause INFORMIX-4GL to check before accepting an input value.

Syntaxfield-tag = [ table. ] column, INCLUDE = ( { value | value TO value } [ , . . . ] );

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

INCLUDE = is a keyword, followed by an equal ( = ) sign.

value 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, sepa-rated by commas.

TO is a keyword that separates the lower and upper limits of arange of values.

Notes1. 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-OnlyFields” 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 nega-tive value; or the earlier DATE or DATETIME value; or the string that startswith a character closer to the beginning of the ASCII collating sequence.)

3. For ranges of character values, INFORMIX-4GL uses dictionary orderwithin the printable ASCII character set. (See Appendix H for the ASCIIcollating 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 thestring ‘‘5,’’ since 1 comes before 5 in the ASCII character set.

4-36 Form Building and Compiling

Page 261: Manual Informix

INCLUDE

4. If you include a character string that contains a blank space, a comma, orany special characters, or does not begin with a letter, you must enclosethe entire string in quotation marks. It is advisable to enclose characterstrings in quotation marks at all times.

5. The user must enter an acceptable value in any display field with theINCLUDE attribute before INFORMIX-4GL accepts a new row.

6. If the list of acceptable values in the value-list does not include the defaultvalue, the INCLUDE attribute behaves like the REQUIRED attribute, andan acceptable entry is required.

7. Including a COMMENTS attribute to indicate acceptable values makesdata entry easier.

Examplei18 = items.quantity, include = (1 to 50),

comments = "Acceptable values are 1 through 50";

Related AttributesCOMMENTS, REQUIRED

Form Building and Compiling 4-37

Page 262: Manual Informix

NOENTRY

NOENTRY

OverviewUse the NOENTRY attribute to prevent data entry during an INPUT orINPUT ARRAY statement.

Syntaxfield-tag = [ table. ] column, NOENTRY;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

NOENTRY is a keyword indicating that no data can be entered in thefield by an INPUT or INPUT ARRAY statement.

NoteThe NOENTRY attribute does not prevent data entry into a field during aCONSTRUCT statement (for a query by example).

Examplei13 = items.stock_num; = stock.stock_num, NOENTRY;

When you are entering data into the stock table, the stock_num column is notavailable, since this SERIAL column gets its value from INFORMIX-4GL dur-ing the INSERT statement. You can, however, use the same field to enter thestock number intended for the items table.

4-38 Form Building and Compiling

Page 263: Manual Informix

PICTURE

PICTURE

OverviewUse the PICTURE attribute to specify the character pattern for data entry to acharacter field.

Syntaxfield-tag = [ table. ] column, PICTURE = "format-string";

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

PICTURE = is a keyword, followed by an equal ( = ) sign.

format-string is a string of characters (enclosed in quotes) to specify thedesired character pattern.

Notes1. A format-string can include three special symbols:

Symbol MeaningA Any letter# Any digitX 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 andleaves 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 theformat-string, the terminal beeps, and INFORMIX-4GL does not echothe character on the screen.

5. The PICTURE attribute does not require the entry of the entire field. Itonly requires that whatever the user enters conforms to format-string.

Form Building and Compiling 4-39

Page 264: Manual Informix

PICTURE

6. When PICTURE formats DATETIME or INTERVAL fields, FORM4GL doesnot check the syntax of format-string, but your form will work if the syntaxis correct. Any error in format-string, however, such as an incorrect fieldseparator, produces a run-time error.

ExamplesThe 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-4GLincludes them in the string that it passes to the program variable.

Related AttributeFORMAT

4-40 Form Building and Compiling

Page 265: Manual Informix

REQUIRED

REQUIRED

OverviewUse the REQUIRED attribute to force data entry in a particular field duringan INPUT or INPUT ARRAY statement.

Syntaxfield-tag = [ table. ] column, REQUIRED;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

REQUIRED is the keyword that instructs INFORMIX-4GL to insist upondata entry to the field-tag field.

Notes1. 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 theREQUIRED attribute and the DEFAULT attribute to the same field, INFOR-MIX-4GL assumes that the DEFAULT value satisfies the REQUIREDattribute.

3. The REQUIRED attribute requires only that the user enter a printablecharacter in the field. If the user subsequently erases the entry during thesame input, INFORMIX-4GL considers the REQUIRED attribute satisfied. Ifyou want to insist on a non-NULL entry, make the field form-only andNOT NULL.

ExampleIf your ATTRIBUTES section includes the field description

o20 = orders.po_num, REQUIRED;

INFORMIX-4GL requires the entry of a purchase order value when you collectinformation for a new order.

Form Building and Compiling 4-41

Page 266: Manual Informix

REQUIRED

Related AttributeNOENTRY

4-42 Form Building and Compiling

Page 267: Manual Informix

REVERSE

REVERSE

OverviewAssign the REVERSE attribute to fields that you want INFORMIX-4GL todisplay in reverse video (dark characters in a bright field).

Syntaxfield-tag = [ table. ] column, REVERSE;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

REVERSE is the keyword that instructs INFORMIX-4GL to display thefield-tag field in reverse video.

Notes1. 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 isactive.

Examplef000 = customer.customer_num, reverse;

Related AttributeCOLOR

Form Building and Compiling 4-43

Page 268: Manual Informix

UPSHIFT

UPSHIFT

OverviewAssign the UPSHIFT attribute to a character field when you want INFOR-MIX-4GL to convert lowercase letters in data entry to uppercase letters, bothon the screen and in the program variable corresponding to that field.

Syntaxfield-tag = [ table. ] column, UPSHIFT;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

UPSHIFT is the keyword that instructs INFORMIX-4GL to convertcharacter input data to uppercase.

NoteBecause uppercase and lowercase letters have different ASCII values, storingall character strings in one or the other format can simplify sorting and que-rying a database.

Examplec8 = state, UPSHIFT, AUTONEXT,

INCLUDE = ("CA", "OR", "NV", "WA"),DEFAULT = "CA" ;

Because of the UPSHIFT attribute, INFORMIX-4GL enters uppercasecharacters in the state field regardless of the case used to enter them.

The AUTONEXT attribute tells INFORMIX-4GL to move automatically to thenext field once you type the total number of characters allowed for the field(in this instance, two characters). The INCLUDE attribute restricts entry in thisfield to the characters CA, OR, NV, or WA only. The DEFAULT value for the fieldis CA.

4-44 Form Building and Compiling

Page 269: Manual Informix

UPSHIFT

Related AttributeDOWNSHIFT

Form Building and Compiling 4-45

Page 270: Manual Informix

VALIDATE LIKE

VALIDATE LIKE

OverviewUse the VALIDATE LIKE attribute to cause INFORMIX-4GL to validate thedata entered into the field, using the default attributes assigned to a databasecolumn in the syscolval table.

Syntaxfield-tag = [ table. ] column, VALIDATE LIKE tbl.col;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

VALIDATE LIKE are required keywords.

tbl.col is the name of a database column

Notes1. This attribute is equivalent to listing all the attributes that you have

assigned to tbl.col in the syscolval table. A later section, ‘‘Default ScreenAttributes,’’ describes the syscolval table.

2. You do not need the VALIDATE LIKE attribute if table.column is the sameas tbl.col.

3. Do not use columns of type DATETIME or INTERVAL for tbl.col.

Examples13 = formonly.state, VALIDATE LIKE customer.state;

Related AttributeDISPLAY LIKE

4-46 Form Building and Compiling

Page 271: Manual Informix

VERIFY

VERIFY

OverviewUse the VERIFY attribute when you want INFORMIX-4GL to require users toenter data twice for a particular field, in order to reduce the probability oferroneous data entry.

Syntaxfield-tag = [ table. ] column, VERIFY;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a field (either related to a column orFORMONLY).

VERIFY is the keyword that instructs INFORMIX-4GL to requireduplicate data entry to the field-tag field.

NoteSince some data are critical, this attribute supplies an additional step in dataentry to ensure the integrity of your data. After the user enters a value into aVERIFY field and presses RETURN, INFORMIX-4GL erases the field andrequests reentry of the value. The user must enter exactly the same data eachtime, character for character: 15000 is not exactly the same as 15000.00 .

ExampleIf 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

Page 272: Manual Informix

WORDWRAP

WORDWRAP

OverviewUse the WORDWRAP attribute in a multiple-line field to enable the multilineeditor. This attribute wraps a long character string to the next line of a multi-ple-line field for data entry and display.

Syntaxfield-tag = [ table. ] column, WORDWRAP [ COMPRESS ] ;

Explanationfield-tag is the field tag used in the SCREEN section.

table.column is the name of a multiple-line field (either related to a columnor FORMONLY).

WORDWRAP is a keyword to wrap long character strings to the next seg-ment of a multiple-line field.

COMPRESS is a keyword to discard any blank spaces that the user didnot enter and that are not part of the data.

Notes1. 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-rightand top-to-bottom order.

2. When text is entered into a multiple-line field whose attributes includeWORDWRAP, the multiline editor breaks character strings into segmentsat 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 bringsthe current word down to the next line, moving text down to subsequentlines as necessary. When the user deletes text, the editor pulls words upfrom 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 TABcharacter aligns the display at the next tab stop, while NEWLINE moves

4-48 Form Building and Compiling

Page 273: Manual Informix

WORDWRAP

the display to the start of the next line. Tab stops are in every eighthcolumn, beginning at the left-hand edge of the field.

5. Ordinarily, the length of the variable should not be greater than the totallength of the field. When the data is longer than the field (or if too muchpadding is required for WORDWRAP), the multiline editor fills the fieldand discards the excess data. This allows a long variable to be shown insummary form. If a truncated variable is used to update the database,however, data will be lost.

6. The editor distinguishes between intentional blanks (from the database ortyped by the user) and editor blanks (inserted at the ends of lines for word-wrap or to align after a NEWLINE). Intentional blanks are retained as partof the data. Editor blanks are inserted and deleted automatically asrequired for word-wrapping.

7. When designing a multiple-line field, you should allow room for editorblanks, over and above the variable length. The expected number of edi-tor blanks is half the length of an average word per line. Text that requiresmore space than you expect might be truncated after the final line of thefield.

8. The COMPRESS keyword prevents blanks produced by the editor frombeing included in the program variable. If you specify COMPRESS, trun-cation occurs only if the sum of intentional characters exceeds the columnsize. But the stored data does not correspond to its multiline display, so areport cannot display it in identical form.

9. If you omit COMPRESS, all blanks are retained in the variable, even editorblanks, and the contents of a variable reflect its multiline display. Forexample, a report could duplicate its appearance by printing successivesubstrings the width of a display segment. If the sum of the field segmentlengths exceeds the length of the variable, some trailing characters mightbe truncated.

10. An earlier section, ‘‘Multiple-Line Fields,’’ describes the SCREEN sectionspecifications for multiple-line fields.

11. When data is entered or updated in a WORDWRAP field, the user can usekeys that are described in this note to move the screen cursor over thedata, and to insert, delete, and type over the data. The cursor neverpauses 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 aNEWLINE. If the cursor in typeover mode encounters a NEWLINE charac-ter, the cursor mode automatically changes to insert, ‘‘pushing’’ theNEWLINE character to the right. Some keystrokes behave differently inthe two modes.

Form Building and Compiling 4-49

Page 274: Manual Informix

WORDWRAP

When the cursor first enters a multiline field, it is positioned on the firstcharacter of the first segment, and the mode is set to typeover. The cursormovement keys are as follows:

RETURN leaves the entire multiline field, and goes to the firstcharacter of the next field.

BACKSPACEorLEFT ARROW

moves left one character, unless at the left edge of asegment. From the left edge of the first segment, theseeither move to the first character of the preceding field,or only beep, depending on input wrap mode. (Inputwrap mode is controlled by the OPTIONS statement.)From the left edge of a lower segment, these move tothe rightmost intentional character of the next highersegment.

RIGHT ARROW moves right one character, unless at the rightmostintentional character in a segment. From the rightmostintentional character of the last segment, this eithermoves to the first character of the next field, or onlybeeps, depending on input wrap mode. From the right-most intentional character of a higher segment, thismoves to the first intentional character in a lower seg-ment.

UP ARROW moves from the topmost segment to the first characterof the preceding field. From a lower segment, thismoves to the character in the same column of the nexthigher segment, jogging left, if required, to avoid edi-tor blanks, or if it encounters a TAB.

DOWN ARROW moves from the lowest segment to the first characterof the next field. From a higher segment, moves to thecharacter in the same column in the next lowersegment, jogging left if required to avoid editor blanks,or if it encounters a TAB.

TAB inserts a TAB character, in insert mode, and moves thecursor to the next TAB stop. This can cause followingtext to jump right to align at a TAB stop. In typeovermode, this moves the cursor to the next TAB stop thatfalls on an intentional character, going to the next fieldsegment if required.

The character keys enter data. Any following data shifts right, and wordscan move down to subsequent segments. This can result in characters

4-50 Form Building and Compiling

Page 275: Manual Informix

WORDWRAP

being discarded from the final segment of the field. The other keystrokesthat alter data are:

CONTROL-A switches between typeover and insert mode.

CONTROL-X deletes the character under the cursor, possibly caus-ing words to be pulled up from subsequent segments.

CONTROL-D deletes all text from the cursor to the end of the multi-ple-line field (not merely to the end of the current fieldsegment).

CONTROL-N inserts a NEWLINE character, causing subsequent textto align at the first column of the next segment of thefield, and possibly moving words down to subsequentsegments. This can result in characters being discardedfrom the final segment of the field.

12. The appearance on the screen of a character value can vary, depending onwhether or not it is displayed in a multiple-line WORDWRAP field. Forinstance, if a value prepared using WORDWRAP is displayed without it,words will be broken, not wrapped, and tabs and newlines will displayas question marks. This does not represent any loss of data, only a differ-ent mode of display.

If a value prepared under the multiline editor is again edited withoutWORDWRAP, however, some formatting may be lost. For example, a usermight type over a TAB or NEWLINE, not realizing what it was. A usermight remove a blank from the first column of a line, and thus join a wordto the last word on the previous line. These mistakes will be visible whenthe value is next displayed in a WORDWRAP field or in a 4GL report thatuses the WORDWRAP function.

13. If you also have INFORMIX-SQL installed on your system, you can usethe SQL Interactive Editor to display character data that you preparedusing WORDWRAP. Since the default screen display of the Interactive Edi-tor does not wrap words, words will appear broken, not wrapped, andTAB and NEWLINE characters will appear as question marks ( ? ). Thisdoes not represent any loss of data, only a different mode of display.

Form Building and Compiling 4-51

Page 276: Manual Informix

INSTRUCTIONS Section

ExampleIn the following form specifications, a CHAR value in the column charcolm isdisplayed in the multiple-line field whose tag is mlf.

SCREEN SIZE 24 by 80{Enter text:

[mlf ][mlf ]

. . .[mlf ][mlf ]

}

TABLES table t . . .

ATTRIBUTESmlf = tablet.charcolm, WORDWRAP COMPRESS;

If the data string is too long to fit in the first line, successive segments will bedisplayed in successive lines, until all of the lines are filled, or until the lasttext character is displayed (whichever happens first).

If the form is used to insert data into tablet.charcolm, the keywordCOMPRESS specifies that INFORMIX-4GL will not store editor blanks. Do notuse a comma between the keywords WORDWRAP and COMPRESS.

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

INSTRUCTIONS SectionThe INSTRUCTIONS section is the optional final section of a form specificationfile. You can use this section to specify non-default field delimiters, and todefine screen records and screen arrays. It appears after the last field descrip-tion (or after the optional END keyword) of the ATTRIBUTES section. It hasthis structure:

SyntaxINSTRUCTIONS

{ delimiters| record| array }. . .

[ END ]

4-52 Form Building and Compiling

Page 277: Manual Informix

INSTRUCTIONS Section

ExplanationINSTRUCTIONS is a required keyword to mark the beginning of the

INSTRUCTIONS section.

delimiters specifies two non-default screen field delimiters.

record specifies a screen record.

array specifies an array of screen records.

END is an optional keyword to mark the end of theINSTRUCTIONS section.

Notes1. 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 fieldswhen the form appears on the screen from brackets ( [ ] ) to any other print-able character, including blank spaces.

Syntax

DELIMITERS "ab"

Explanation

DELIMITERS is a keyword to specify field delimiters.

a is the opening field delimiter.

b is the closing field delimiter.

Notes

1. The DELIMITERS instruction tells INFORMIX-4GL what symbols to use asfield delimiters when it displays the form on the screen.

2. FORM4GL requires brackets ( [ ] ) in the SCREEN section of a formspecification file, regardless of any DELIMITERS instruction.

3. You must enclose the pair of ab symbols in quotation ( " ) marks.

Form Building and Compiling 4-53

Page 278: Manual Informix

INSTRUCTIONS Section

4. Each delimiter occupies a space, so two fields on the same line areordinarily separated by at least two spaces. If you want only one spacebetween consecutive screen fields, follow these two steps:

(1) In the SCREEN section, substitute a vertical bar ( | ) for pairedback-to-back ( ][ ) brackets that separate adjacent fields.

(2) In the INSTRUCTIONS section, define some symbol as both thebeginning and ending delimiter. For example, you could specify"| |" or "/ /" or ": :" or " " (blanks).

Examples

The following specifications display < and > as opening and closing delimit-ers of screen fields:

INSTRUCTIONSDELIMITERS "<>"

END

The following specifications substitute | for ][ between adjacent fields in thesame line of the screen layout, and display a colon ( : ) as both the openingand closing delimiter:

SCREEN{

. . .Full Name-[f011 |f012 ]

. . .}

. . .INSTRUCTIONS

DELIMITERS "::"

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 boundariesare not marked (or are only marked if they have attributes that contrast withthe surrounding background).

4-54 Form Building and Compiling

Page 279: Manual Informix

INSTRUCTIONS Section

Screen Records

You can collect groups of screen fields into screen records. Define any screenrecords in the INSTRUCTIONS section of a form specification file, and refer tothem in your INFORMIX-4GL program.

Syntax

SCREEN RECORD record-name( { table.*

| table.column1 THRU table.column2| table.column } [ , . . . ] )

ExplanationSCREENRECORD

are keywords to define a list of fields as a screen record oras a screen array.

record-name is an SQL identifier for the screen record.

table is a table name, alias, or synonym (or the keywordFORMONLY).

column1,column2,column

are field names that you defined in the ATTRIBUTES section.(These identifiers link the fields to database columns, unlessyou specify table as FORMONLY.)

THRU is an optional keyword to specify consecutive fields. Thekeyword THROUGH is a synonym.

Notes

1. A screen record or screen array can include fields with different tablespecifications, including FORMONLY.

2. FORM4GL automatically creates a default screen record for each table thatis used to identify a field in the form specification file. The default record,which has the name of the table, contains components corresponding toonly those columns in the table that are fields on the form. The order ofcomponents in a screen record is the order of the field names in theATTRIBUTES section. Use table.* to denote the same fields as the defaultrecord for table.

3. FORM4GL returns an error if you define a screen record with the samename 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 theATTRIBUTES section. The THRU keyword is shorthand for listing all fields

Form Building and Compiling 4-55

Page 280: Manual Informix

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 tosome columns of the customer table. This record can simplify 4GL statementsto 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 defaultscreen record whose record-name is customer.

Screen Arrays

You can collect groups of screen fields into screen arrays. A screen array isusually an array of lines on the form, each containing identical groups ofscreen fields. Each ‘‘column’’ of a screen array consists of fields with the sametag. Define screen arrays in the INSTRUCTIONS section, and refer to them inyour 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 theaddition of [ n ] as a required integer parameter, enclosed in brackets. (Inthis 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

Page 281: Manual Informix

Default Screen Attributes

Example

To illustrate a typical screen array, consider the following fragment of a formspecification file:

SCREEN{...Item 1 [p ][q ][u ][t ]Item 2 [p ][q ][u ][t ]Item 3 [p ][q ][u ][t ]Item 4 [p ][q ][u ][t ]Item 5 [p ][q ][u ][t ]}

TABLES orders items stock

ATTRIBUTES...p = stock.stock_num;q = items.quantity;u = stock.unit_price;t = items.total_price;...INSTRUCTIONSSCREEN 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 fieldslinked to columns from two database tables. The rows are numbered from1 to 5.

If there are no other columns of the items table in the form, the defaultscreen record items contains two fields, corresponding to the quantityand total_price columns of the items table.

Default Screen AttributesAs an alternative to entering attributes in the form specification file, you canenter them into two database tables, syscolval and syscolatt, using theupscol utility described in Appendix E. During compilation of a form,FORM4GL searches these tables for data validation and screen attributeinformation about screen fields whose names correspond to database col-umns. FORM4GL adds the attributes listed in these tables to attributes listedin the form specification file. In case of conflict, attributes explicitlymentioned in the form specification file take priority.

Form Building and Compiling 4-57

Page 282: Manual Informix

Default Screen Attributes

INFORMIX-4GL enforces the resulting set of field attributes during theexecution 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 syscolatttabname char(18) tabname char(18)colname char(18) colname char(18)attrname char(10) seqno serialattrval char(64) 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 whichthe attributes apply. Here colname cannot be a DATETIME or INTERVAL col-umn. Permissible values for the attrname and attrval columns in syscolvalare shown in the following table:

attrname attrvalINCLUDE as in this chapterPICTURE as in this chapterDEFAULT as in this chapterCOMMENTS as in this chapterSHIFT UP, DOWN, NO (the default)VERIFY YES, NO (the default)AUTONEXT YES, NO (the default)

The color column in syscolatt stores an integer that describes color (for colorterminals) or intensities (for monochrome terminals).

The next table shows the displays specified by each value of color, and thecorrespondence between default color names and intensities.

Number Color Terminal Monochrome Terminal0 White Normal1 Yellow Bold2 Magenta Bold3 Red Bold†4 Cyan Dim5 Green Dim6 Blue Dim†7 Black Invisible

4-58 Form Building and Compiling

Page 283: Manual Informix

Default Screen Attributes

The background for colors is BLACK in all cases. The † signifies that, if thekeyword BOLD is indicated as the attribute, the field will be RED on a colorterminal; or, if the keyword DIM is indicated as the attribute, the field will beBLUE on a color terminal.

You can also define non-default names for colors, by associating differentnames 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 examinescolornames at compile time to obtain the correspondence between the num-bers 0 through 7 and the color names. Those names can appear in theATTRIBUTE clause of a 4GL statement. (But you cannot use numbers or non-default colors from colornames to specify the COLOR attribute in a formspecification file.)

The values for inverse, underline, and blink are Y (yes) and N (no). Thedefault for each of these columns is N, that is, normal display (bright charac-ters in a dark field), no underline, and steady font. Which of these attributescan be displayed simultaneously with the color combinations or with eachother is terminal-dependent.

The def_format column takes the same string that you would enter for theFORMAT attribute in a screen form. Do not use quotation marks.

The condition column takes string values that are a restricted set of theWHERE clauses of a SELECT statement, except that the WHERE keyword andthe column name are omitted. INFORMIX-4GL assumes that the value in thecolumn identified by tabname and colname is the subject of all comparisons.

Examples of permitted entries for the condition column follow:

<= 100 MATCHES "[A-M]*"BETWEEN 101 AND 1000 IN ("CA", "OR", "WA")>= 1001 NOT LIKE "%analyst%"

The VALIDATE statement checks a program record or variable list againstsyscolval. The INITIALIZE statement looks up the default values that arelisted 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 canspecify these attributes:

WHITE = NORMAL BLUE = DIMYELLOW = BOLD BLACK = INVISIBLEMAGENTA = BOLD REVERSERED = BOLD BLINKCYAN = DIM UNDERLINEGREEN = DIM

Form Building and Compiling 4-59

Page 284: Manual Informix

The upscol Tables in a MODE ANSI Database

On color terminals, NORMAL is interpreted as WHITE; BOLD as RED; DIM asBLUE; and INVISIBLE as BLACK. If you have a colornames file, you can alsouse the color names or numbers listed there.

You can override the default attributes in syscolatt by assigning otherattributes in the form specification file, or in the ATTRIBUTE clause of theINFORMIX-4GL CONSTRUCT, DISPLAY, DISPLAY ARRAY, INPUT, or INPUTARRAY statement. When one of these is the current statement and includesan ATTRIBUTE clause, INFORMIX-4GL displays only the attributes in thatclause. There is no carry-over of unmentioned display attributes from thecompiled form (except FORMAT). For example, if a column is designated asRED 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 statedearlier, form specification file attributes take precedence over the defaultsyscolatt attributes. A note describing the OPTIONS statement in Chapter 7lists the order of precedence among different sources of attribute specifica-tions, if these are in conflict.

Unconditional color or intensity attributes are available through theATTRIBUTE clause. These and conditional attributes are also supported bysyscolatt and by the COLOR keyword in the ATTRIBUTES section. You can usethe upscol utility, described in Appendix E, to specify default attributes insyscolval and syscolatt.

The color, intensity, and other screen attributes interact with termcap or ter-minfo files on UNIX systems. Appendix I describes the changes that shouldbe made in system information files to support these display features foryour terminal. Systems that use terminfo files rather than termcap, however,support no INFORMIX-4GL display attributes except REVERSE and UNDER-LINE.

The upscol Tables in a MODE ANSI DatabaseIn a database that is not MODE ANSI, the default screen attributes and valida-tion criteria that you specify with the upscol utility are stored in two tables,syscolval and syscolatt. If any user of upscol assigns default values orattributes to a database column, those defaults are available to every user ofa form that references the column.

4-60 Form Building and Compiling

Page 285: Manual Informix

Creating and Compiling a Form

In a database that is started or created as MODE ANSI, however, separateowner.syscolval and owner.syscolatt tables are created for each user of theupscol utility. These tables store the default specifications of that individualuser. Which set of upscol tables is used by FORM4GL depends on the natureof the request.

If the TABLES section specifies a table alias for owner.table, FORM4GL uses theupscol tables of the owner of table. If that user owns no upscol tables, nodefaults are assigned to fields associated with that table alias. If the TABLESsection of the form does not specify a table alias that includes the owner of adatabase table, the upscol tables owned by the user running FORM4GL areapplied to fields associated with that database table, unless the user owns noupscol 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 forowner.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 notthe correct owner, the compilation fails and an error message is issued.

See also the notes in Chapter 7 on the VALIDATE and INITIALIZE statementsof INFORMIX-4GL.

Creating and Compiling a FormYou can create a form specification file and its customized screen form eitherthrough the INFORMIX-4GL Programmer’s Environment or directly from theoperating system. Either alternative requires that you have already createdthe database and all the tables to which the form refers. The next two subsec-tions describe these alternative procedures.

Form Building and Compiling 4-61

Page 286: Manual Informix

Through the Programmer’s Environment

Through the Programmer’s EnvironmentTo create a screen form using the Programmer’s Environment (which isdescribed 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 canselect the New option. INFORMIX-4GL prompts you for a form name,prompts you for an editor if you have not already selected one, andinvokes that editor with an empty form specification file. Now you mustenter form specifications. The Generate option is usually a more efficientway to create a customized form.)

3. Enter the name of the database and the name that you want to assign tothe form (for example, myform). INFORMIX-4GL asks you for the namesof the tables whose columns you want in your form. After you select thetables, FORM4GL creates a default form specification file, as well as acompiled default form, and then displays the FORM Design Menu.

4. The default form specification file formats the screen as a list of all thecolumns in the tables that you entered in Step 3. It does not provide anyspecial instructions to INFORMIX-4GL about how to display the data.Select the Modify option, and INFORMIX-4GL presents the MODIFYFORM Screen. Select the default form specification (given as myformearlier), and INFORMIX-4GL calls a system editor to display the file. Editthe default form specification file to produce your customized screenform and associated instructions. (You can specify an editor using theDBEDIT environment variable. This is fully explained in Appendix C.)When you save your file and quit the editor, you return to theMODIFY 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 notcompile successfully, go on to Step 6.

6. Select the Correct option from the COMPILE FORM Menu. INFORMIX-4GLagain calls your editor to display the form specification file, with the com-pilation errors marked. When correcting your errors, you need not deletethe error messages. INFORMIX-4GL does that for you. Save the file and goto Step 5.

7. Save your form specification file with the Save-and-exit option.

4-62 Form Building and Compiling

Page 287: Manual Informix

Through the Operating System

Through the Operating SystemThe 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 numberof lines of characters (measured vertically) that the terminal candisplay. (The default is 24.)

-c cols are optional symbols and an integer to specify the width of thescreen, in characters. (The default is the number of characters inthe longest line of the screen layout, as specified in the SCREENsection.)

-v are optional characters to verify that the screen fields are aswide as any corresponding character fields specified in theATTRIBUTES section.

form-name is the name of the form specification file (without the .perextension).

-d are optional symbols to specify a default form specification file.

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 yourform specification file, the name of your database, and the name of a tablewhose columns you want in your form. It continues to ask for anothertable name until you enter a RETURN for the name of a table. FORM4GLthen creates a default form specification file and appends theextension .per to its name. It also creates a compiled default form withthe extension .frm.

2. Use the system editor to modify the default form specification file to meetyour specifications. If, as an alternative, you create a new form specifica-tion file and skip Step 1, be sure to give the filename the extension .per.

Form Building and Compiling 4-63

Page 288: Manual Informix

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 .perextension).

If the compilation is successful, FORM4GL creates a compiled form filecalled myform.frm and you are finished creating your customized screenform. If not, FORM4GL instead creates a file named myform.err, and youneed to go on to Step 4.

4. Review the file myform.err to discover the compilation errors. Makecorrections in the file myform.per. Go to Step 3.

Using PERFORM Forms in INFORMIX-4GLIf you have designed forms to use with the PERFORM screen transactionprogram of INFORMIX-SQL, you need to know how those forms behavewhen used with INFORMIX-4GL. The following features differ betweenPERFORM and INFORMIX-4GL:

• Only the DELIMITER keyword in the INSTRUCTIONS section of aPERFORM form specification is supported in INFORMIX-4GL. Otherkeywords in that section are ignored. For the same effects, you must codethem into your INFORMIX-4GL program. (See the BEFORE and AFTERclauses of the INPUT statement.)

• Multiple-page forms will not work with INFORMIX-4GL and willproduce undesirable overlays. (You can use multiple forms in 4GL toproduce the effects of forms having several pages.)

• There is no concept of ‘‘current table’’ in INFORMIX-4GL. A single INPUTor INPUT ARRAY statement allows you to enter data into fields thatcorrespond to columns in different tables.

• Joins defined in the PERFORM form specification are ignored in INFOR-MIX-4GL. You can associate two field names with the same field tag, usingthe same notation as in a PERFORM join, but no join is effected. On theother hand, you can create more complex joins and look-upsin INFORMIX-4GL using the full power of SQL.

• The PERFORM attributes LOOKUP, NOUPDATE, QUERYCLEAR, RIGHT,and ZEROFILL are inoperative in INFORMIX-4GL, and the conditionsof a COLOR attribute cannot reference other field tags nor aggregatefunctions.

• The default attributes listed in syscolval and syscolatt do not applyto your PERFORM forms unless you recompile them.

4-64 Form Building and Compiling

Page 289: Manual Informix

Chapter

5

Report WritingChapter Overview 3

Calling a REPORT Routine 4

Structure of a REPORT Routine 5DEFINE Section 7OUTPUT Section 9REPORT TO 10LEFT MARGIN 12RIGHT MARGIN 13TOP MARGIN 15BOTTOM MARGIN 16PAGE LENGTH 17ORDER BY Section 18FORMAT Section 20EVERY ROW 21Control Blocks 23AFTER GROUP OF 25BEFORE GROUP OF 27FIRST PAGE HEADER 29ON EVERY ROW 31ON LAST ROW 33PAGE HEADER 34PAGE TRAILER 36Statements 37

Standard 4GL Statements 37Statements Valid Only in the FORMAT Section 37

NEED 38PAUSE 39PRINT 40PRINT FILE 42SKIP 43Expressions and Built-in Functions 44

Page 290: Manual Informix

Aggregates 46LINENO 48PAGENO 49SPACES 50WORDWRAP 51

5-2 Report Writing

Page 291: Manual Informix

Chapter OverviewINFORMIX-4GL provides all the tools of a general-purpose relational reportwriter. Reports in INFORMIX-4GL have the following features:

• You have full control over page layout for your 4GL report. This includesfirst-page headers that differ from headers on subsequent pages, pagetrailers, columnar data presentation, special formatting before and aftergroups of sorted data, and conditional formatting that depends on thedata.

• INFORMIX-4GL provides aggregate functions that enable you to computepercentages, sums, averages, maximums, and minimums.

• You can use the WORDWRAP function to display long character stringsthat occupy multiple lines of output.

• You can use all the built-in functions of INFORMIX-4GL and the USINGoperator. (Chapter 2 describes USING and the built-in 4GL functions andexpressions.)

• You can create the report either from the rows returned by a cursor orfrom report records assembled from any other source, such as the outputof 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 INFOR-MIX-4GL statements in the middle of writing a report if the intermediatevalues calculated by the report meet your criteria. For example, you couldeven 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 exam-ples of REPORT routines.)

Report Writing 5-3

Page 292: Manual Informix

Calling a REPORT Routine

Calling a REPORT RoutineTo call a REPORT routine requires three 4GL statements that occur before,during, and after a program loop that you define. You can call a REPORTroutine 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 programblock

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 illus-trated as follows:

START REPORT report1begin loop -- of whatever kind

. . .OUTPUT TO REPORT report1(customer.*). . .

end loopFINISH REPORT report1

• The START REPORT statement initializes the report and optionallyspecifies the output file or device.

• The OUTPUT TO REPORT statement tells INFORMIX-4GL to process thenext row of the report.

• The FINISH REPORT statement causes the ON LAST ROW control blockto be executed, if it is present, so that INFORMIX-4GL can produce theend-of-report summaries.

You can find the full syntax for these statements in Chapter 7.

5-4 Report Writing

Page 293: Manual Informix

Structure of a REPORT Routine

Structure of a REPORT RoutineLike the MAIN program block or a function of a 4GL program, a report is asequence of consecutive statements within a 4GL source file.

A REPORT routine is composed of sections that consist of control blocksor statements, or both. Each statement can contain clauses made up ofkeywords and expressions. You must observe the order of the sections thatfollow when you write an INFORMIX-4GL REPORT routine.

• DEFINE Section: This section declares the data types of any programvariables or records that are passed as arguments to the report by thecalling statement, and of any local variables or records that are usedwithin the report. Reports that do not have such arguments or localvariables do not require a DEFINE section.

• OUTPUT Section: This optional section specifies a non-default pagelength and margins for the physical format of the report, and specifieswhether INFORMIX-4GL sends the report to the screen, to a file, or toanother program.

• ORDER BY Section: This optional section specifies the variables on whichyou want rows to be sorted, and the order in which 4GL will process anygroup control blocks that you specify in the FORMAT section.

• FORMAT Section: This required section specifies the appearance of thereport, including page headers, page trailers, and aggregate functions ofthe data. Control blocks can specify actions to take before or after specificgroups of rows are processed, using any INFORMIX-4GL statement,expression, or function. Control blocks can also include certain state-ments and functions that are only recognized within the FORMAT sectionof a REPORT routine.

Each section begins with the keyword for which it is named. These elementsof a REPORT routine are described in the pages that follow.

The first statement of a REPORT routine must be the REPORT statement, andthe last must be the END REPORT statement:

SyntaxREPORT report-name (argument-list)

[ DEFINE section ][ OUTPUT section ][ ORDER BY section ]FORMAT section

END REPORT

Report Writing 5-5

Page 294: Manual Informix

Structure of a REPORT Routine

ExplanationREPORT is a required keyword.

report-name is an INFORMIX-4GL identifier.

(argument-list) is a list of variables or record identifiers, enclosed in paren-theses and separated by commas.

END REPORT are required keywords.

Notes1. Record identifiers cannot have the asterisk ( .* ) extension in argument-list.

2. The DEFINE, OUTPUT, ORDER BY, and FORMAT sections are described inlater sections of this chapter.

3. A minimal report consists only of the FORMAT section. You can includeother sections as needed.

ExamplesSeveral REPORT routines are included with the demonstration applicationlisted in Appendix A. They illustrate many of the commands available forwriting reports with INFORMIX-4GL, and provide some of the examples thatappear in this chapter.

5-6 Report Writing

Page 295: Manual Informix

DEFINE Section

DEFINE SectionAn INFORMIX-4GL REPORT routine requires a DEFINE section when you passarguments to the report or use local variables in the report.

SyntaxDEFINE variable-list { type | LIKE table.column

| RECORD { LIKE table.* | variable-list type [ , . . . ]END RECORD } } [ , . . . ]

ExplanationDEFINE is a required keyword.

variable-list is one or more identifiers of program variable.

type is one of these data types (as defined in Chapter 2):

SMALLINT MONEY [ (m [ , n ] ) ]

INTEGER CHAR [ ( n ) ]INT CHARACTER [ (n ) ]

DECIMAL [ (m [ , n ] ) ] DATEDEC [ ( m [ , n ] ) ]NUMERIC [ (m [ , n ] ) ] DATETIME qualifier

SMALLFLOAT INTERVAL qualifierREALRECORD [ LIKE table. * ]FLOAT [ ( n ) ]DOUBLE PRECISION [ ( n ) ]

LIKE is a keyword to specify the data type indirectly.

table.column is the full identifier for a column in the current database. TheDATABASE statement must precede DEFINE statements thatuse indirect typing.

RECORD is a data type that describes a set of variables of possiblydiffering database data types.

table is the name of a database table.

END RECORD are keywords that follow the declaration of the last elementof a program record.

Report Writing 5-7

Page 296: Manual Informix

DEFINE Section

Notes1. The DEFINE section obeys the same rules as given in Chapter 7 for the

DEFINE statement, except that report parameters cannot be of typeARRAY, nor can they be records with ARRAY members.

2. The variable-list must include any local variables that you use inthe report, and any variables or record identifiers that appear in theargument-list of the REPORT statement. You are required to specify anargument-list if any of the following conditions are true:

• When there is an ORDER BY section in your report. In this case, youmust pass all the values for each row of the report.

• When you use the GROUP PERCENT aggregate function anywhere inyour report, or use an aggregate function over all the rows of thereport 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 themiddle of the report, you must pass the rows of the report through theargument-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, youmust pass at least the parameters named in that block.

ExampleREPORT r_invoice (c, stock_tot)

DEFINE c RECORD LIKE customer.*, stock_tot SMALLINT

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

5-8 Report Writing

Page 297: Manual Informix

OUTPUT Section

OUTPUT SectionAn INFORMIX-4GL REPORT routine can contain an OUTPUT section. Thisoptional 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 toan operating system pipe.

The OUTPUT section consists of the OUTPUT keyword, followed by one ormore 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 reportroutine. If you omit this section, output is to the screen.

• The LEFT MARGIN statement specifies how many blank spaces to includeat the left of each line of output. The default is 5 spaces.

• The RIGHT MARGIN statement specifies the maximum number of charac-ters in each line of output, including the left margin. The default is 132characters.

• The TOP MARGIN statement specifies how many blank lines appearbefore the first line on each page of output. The default is 3 lines.

• The BOTTOM MARGIN statement specifies how many blank lines followthe last line on each page of output. The default is 3 lines.

• The PAGE LENGTH statement specifies the total number of lines on eachpage of output, including lines of data, the top and bottom margins, andany 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

Page 298: Manual Informix

REPORT TO

REPORT TO

OverviewThis optional statement directs the output of the INFORMIX-4GL report to afile, an operating system pipe, or the system printer.

SyntaxREPORT TO { "filename" | PIPE "program" | PRINTER }

ExplanationREPORT TO are required keywords.

filename is a quoted string containing the name of a file to receive thereport.

PIPE is an optional keyword.

program is a variable of type CHAR or a quoted string containing thename of a program that is to receive the output from theINFORMIX-4GL report. The program name, and any associ-ated arguments, must be enclosed within quotation ( " )marks.

PRINTER is an optional keyword.

Notes1. You cannot use more than one of the REPORT TO options in a REPORT

routine. When you do not use this optional statement, INFORMIX-4GLsends the report to your screen.

2. If the START REPORT statement has a TO clause directing output of thereport to a file, pipe, or printer, INFORMIX-4GL ignores the REPORT TOstatement of the OUTPUT section.

3. If filename is a variable, you must pass it as an argument to the REPORTroutine.

4. The REPORT TO PRINTER statement causes INFORMIX-4GL to send thereport to the program named by the DBPRINT environment variable. Ifyou do not set this variable, INFORMIX-4GL sends the report to the lpprogram, or to whatever program is the default to access the systemprinter on your implementation of UNIX.

5-10 Report Writing

Page 299: Manual Informix

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, andthen send the file to a printer of your choice. You can also use the REPORTTO PIPE option to direct the output to a program that sends the output tothe correct printer.

ExamplesThe following OUTPUT section directs the report output to the label.outsystem file.

OUTPUTREPORT TO "label.out"LEFT MARGIN 0TOP MARGIN 0BOTTOM MARGIN 0PAGE LENGTH 6

The following OUTPUT section directs the output from the INFORMIX-4GLreport to the more utility.

OUTPUTREPORT TO PIPE "more"

Report Writing 5-11

Page 300: Manual Informix

LEFT MARGIN

LEFT MARGIN

OverviewThis statement sets a left margin for a report.

SyntaxLEFT MARGIN integer

ExplanationLEFT MARGIN are required keywords.

integer is an integer that specifies the width of the left margin, inspaces.

Notes1. The default left margin is five spaces.

2. All columnar displacement indicated by the COLUMN function starts atthe margin set by LEFT MARGIN.

ExampleThe following LEFT MARGIN statement instructs INFORMIX-4GL to print theleft side of the report as far to the left as possible.

OUTPUTREPORT TO "label.out"LEFT MARGIN 0TOP MARGIN 0BOTTOM MARGIN 0PAGE LENGTH 6

5-12 Report Writing

Page 301: Manual Informix

RIGHT MARGIN

RIGHT MARGIN

OverviewThis statement sets a right margin for a report.

SyntaxRIGHT MARGIN integer

ExplanationRIGHT MARGIN are required keywords.

integer is an integer that specifies the width of the text on thepage, in characters.

Notes1. The RIGHT MARGIN determines the right margin by specifying the width

of the page, in characters. This is not dependent on the LEFT MARGIN, butalways starts its count from the left edge of the page, so that the columnsof the LEFT MARGIN are included in the value of RIGHT MARGIN.

2. The RIGHT MARGIN is effective only when the FORMAT section containsan EVERY ROW statement.

3. The default RIGHT MARGIN is 132 characters.

4. INFORMIX-4GL attempts to produce an EVERY ROW report by listing thevariable names across the top of the page, and presenting the data in col-umns beneath these headings. If there is not sufficient room between theLEFT MARGIN and the RIGHT MARGIN to do this, INFORMIX-4GL pro-duces a report that lists the variable names and the data of each row intwo columns.

Report Writing 5-13

Page 302: Manual Informix

RIGHT MARGIN

ExampleThe following example demonstrates the use of the RIGHT MARGIN state-ment. After it processes the OUTPUT section, INFORMIX-4GL sets the rightmargin for the report at 70 characters.

REPORT simple(customer)DEFINE customer LIKE customer.*OUTPUT

RIGHT MARGIN 70

FORMATEVERY ROW

END REPORT

5-14 Report Writing

Page 303: Manual Informix

TOP MARGIN

TOP MARGIN

OverviewThis statement sets a top margin for a report.

SyntaxTOP MARGIN integer

ExplanationTOP MARGIN are required keywords.

integer is an integer that specifies the number of blank lines thatINFORMIX-4GL leaves at the top of each page.

Notes1. The default top margin is three lines.

2. The top margin appears above any page header that you specify in theFORMAT section.

ExampleThe following TOP MARGIN statement instructs INFORMIX-4GL to beginprinting at the top of each page.

OUTPUTREPORT TO "label.out"LEFT MARGIN 0TOP MARGIN 0BOTTOM MARGIN 0PAGE LENGTH 6

Report Writing 5-15

Page 304: Manual Informix

BOTTOM MARGIN

BOTTOM MARGIN

OverviewThis statement sets a bottom margin for a report.

SyntaxBOTTOM MARGIN integer

ExplanationBOTTOM MARGIN are required keywords.

integer is an integer that specifies the number of blank linesthat INFORMIX-4GL is to leave at the bottom of eachpage.

Notes1. The default bottom margin is three lines.

2. The bottom margin appears below any page trailer.

ExampleThe following BOTTOM MARGIN statement instructs INFORMIX-4GL tocontinue printing to the bottom of each page.

OUTPUTREPORT TO "label.out"LEFT MARGIN 0TOP MARGIN 0BOTTOM MARGIN 0PAGE LENGTH 6

5-16 Report Writing

Page 305: Manual Informix

PAGE LENGTH

PAGE LENGTH

OverviewThis statement sets the number of lines on each page of a report.

SyntaxPAGE LENGTH integer

ExplanationPAGE LENGTH are required keywords.

integer is an integer that specifies the length of the page, in lines.

Notes1. The default page length is 66 lines.

2. The PAGE LENGTH includes both the TOP MARGIN and BOTTOMMARGIN.

ExampleThe following example includes a PAGE LENGTH statement:

OUTPUTPAGE LENGTH 22TOP MARGIN 0BOTTOM MARGIN 0

This example specifies that INFORMIX-4GL print each page with 22 lines. Ona standard 24-line video screen, 22 lines is the maximum that you can usewith the PAUSE statement without causing undesirable scrolling.

Report Writing 5-17

Page 306: Manual Informix

ORDER BY Section

ORDER BY SectionThe optional ORDER BY section specifies variables on which to sort rows, andthe order in which to process group control blocks in the FORMAT section. Itsformat is

SyntaxORDER [ EXTERNAL ] BY sort-list

ExplanationORDER BY are required keywords.

EXTERNAL is an optional keyword.

sort-list is a list of one or more variables from the list of arguments tothe REPORT routine.

Notes1. 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 theexact order in which the group control blocks are processed. (Withoutthe ORDER BY section, INFORMIX-4GL chooses the order in whichto process the group control blocks.) In this case, use the EXTERNALkeyword, so that the rows will not be sorted again.

2. The ORDER BY section specifies two things. First, it specifies the order inwhich INFORMIX-4GL orders the input rows. If sort-list contains a, b, andc 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 ofvariable c.

Second, the ORDER BY section specifies the order in which INFOR-MIX-4GL processes group control blocks. (See the section “ControlBlocks” later in this chapter for more information.)

3. The EXTERNAL keyword in the ORDER BY section specifies that the inputrows are already sorted. INFORMIX-4GL does not resort the rows in thiscase.

5-18 Report Writing

Page 307: Manual Informix

ORDER BY Section

4. If there is an ORDER BY section without the EXTERNAL keyword, INFOR-MIX-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 onecursor, you should use the ORDER BY clause in the SELECT statementassociated with the cursor, and use the EXTERNAL keyword in the ORDERBY section of your report.

5. If you have just one variable named in group control blocks and the inputrows are already sorted, then you do not need an ORDER BY section.

ExampleREPORT r_invoice (c, stock_tot)

DEFINE c RECORD LIKE customer.*,stock_tot SMALLINT

ORDER BY stock_tot. . .

Report Writing 5-19

Page 308: Manual Informix

FORMAT Section

FORMAT SectionAn INFORMIX-4GL REPORT routine must contain a FORMAT section. TheFORMAT section determines what a report will look like. It works with thedata that are passed to the routine through the argument list, or with datathat you put in global variables for each row of the report. The FORMATsection begins with the FORMAT keyword, and ends with the END REPORTkeywords.

Two major types of FORMAT sections exist, both of which are described in thefollowing sections. The simplest contains just one EVERY ROW statementbetween the FORMAT and END REPORT keywords. If you use an EVERY ROWstatement, you cannot use any other statements or control blocks:

SyntaxFORMAT

EVERY ROWEND REPORT

More complex FORMAT sections can contain control blocks such as ONEVERY ROW and BEFORE GROUP OF. Each of these control blocks must con-tain at least one FORMAT statement such as PRINT or SKIP n LINES, and theycan contain other statements. If you do not use an EVERY ROW statement, youcan combine control blocks in any order within the FORMAT section. Thistype of non-default FORMAT section has the following structure:

SyntaxFORMAT

[ 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

Page 309: Manual Informix

EVERY ROW

EVERY ROW

OverviewThe EVERY ROW statement causes INFORMIX-4GL to output every row thatyou pass to the report. It uses a default format.

SyntaxEVERY ROW

ExplanationEVERY ROW are required keywords.

Notes1. 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 adefault format.

3. The EVERY ROW statement stands by itself. You cannot modify it with anyof the statements listed in the “Statements” section that appears later inthis chapter.

4. When you use the EVERY ROW statement, you cannot use any controlblocks in the FORMAT section.

5. A report generated by an EVERY ROW statement uses the variable namesthat 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 pro-duces 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 thepage.

7. You can use the RIGHT MARGIN statement in the OUTPUT section tocontrol 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 theON EVERY ROW control block (discussed in the “Control Blocks” sectionlater in this chapter.)

Report Writing 5-21

Page 310: Manual Informix

EVERY ROW

ExamplesThis minimal REPORT routine uses the EVERY ROW statement:

REPORT minimal(customer)DEFINE customer RECORD LIKE customer.*FORMAT

EVERY ROWEND REPORT

Here is a portion of the output from the preceding default specification.

INFORMIX-4GL prints only the column name when the column contains aNULL value.

Following is another example of a brief report specification that uses theEVERY ROW statement. Assume that the cursor used to FETCH rows for thisreport 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

FORMATEVERY ROW

END REPORT

customer.customer_num 101customer.fname Ludwigcustomer.lname Paulicustomer.company All Sports Suppliescustomer.address1 213 Erstwild Courtcustomer.address2customer.city Sunnyvalecustomer.state CAcustomer.zipcode 94086customer.phone 408-789-8075

customer.customer_num 102customer.fname Carolecustomer.lname Sadlercustomer.company Sports Spotcustomer.address1 785 Geary Stcustomer.address2customer.city San Franciscocustomer.state CAcustomer.zipcode 94117customer.phone 415-822-1289

. . .

5-22 Report Writing

Page 311: Manual Informix

Control Blocks

The following display shows the output from the preceding REPORT routine.

Control BlocksControl blocks provide the structure for a customized report. Each controlblock is optional but, if you do not use the EVERY ROW statement, you mustinclude 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 ROWcontrol blocks in a single REPORT routine, INFORMIX-4GL processes allBEFORE GROUP OF blocks before the ON EVERY ROW block and the ONEVERY ROW block before all AFTER GROUP OF blocks. The order in whichINFORMIX-4GL processes the BEFORE GROUP OF control blocks and AFTERGROUP OF control blocks depends upon the hierarchy of variables listed inthe ORDER BY section or, in the absence of an ORDER BY section, implied bythe order of first mention of variables in either BEFORE or AFTER GROUP OFcontrol blocks.

order_num customer_num order_date

1001 104 01/20/19891002 101 06/01/19891003 104 10/12/19891004 106 04/12/19891005 116 12/04/19891006 112 09/19/19891007 117 03/25/19891008 110 11/17/19891009 111 02/14/19891010 115 05/29/19891011 104 03/23/19891012 117 06/05/19891013 104 09/01/19891014 106 05/01/19891015 110 07/10/1989

Report Writing 5-23

Page 312: Manual Informix

Control Blocks

Assume that the ORDER BY section orders by variables a, b, and c. Then thefollowing display indicates the order by which INFORMIX-4GL processescontrol blocks:

BEFORE GROUP OF aBEFORE GROUP OF b

BEFORE GROUP OF cON EVERY ROW

AFTER GROUP OF cAFTER GROUP OF b

AFTER GROUP OF aFigure 5-1 Order of Group Processing

The pages that follow describe these control blocks in alphabetical order.

5-24 Report Writing

Page 313: Manual Informix

AFTER GROUP OF

AFTER GROUP OF

OverviewThe AFTER GROUP OF control block specifies the action that INFORMIX-4GLtakes after it processes a group of rows. Grouping is determined by theordering that you did earlier.

SyntaxAFTER GROUP OF variable-namestatement. . .

ExplanationAFTER GROUP OF are required keywords.

variable-name is the name of one of the variables passed as anargument.

statement is a FORMAT or INFORMIX-4GL statement.

Notes1. 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 givenvariable. INFORMIX-4GL automatically groups rows when you use anORDER BY section in a REPORT routine, or the ORDER BY clause in aSELECT statement. That is, groups are formed when you order a list.

When you specify more than one column in the ORDER BY section orclause, INFORMIX-4GL orders the rows first by the first variable that youspecify (most significant). Rows having the same value on the first vari-able 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 orderedby the last (least significant) variable that you specify.

INFORMIX-4GL processes the statements in an AFTER GROUP OF controlblock each time the specified column changes value, each time a moresignificant column changes value, and at the end of a report. (See Figure5-1 at the beginning of the “Control Blocks” section.)

Report Writing 5-25

Page 314: Manual Informix

AFTER GROUP OF

3. You can have one AFTER GROUP OF control block for each variable onwhich you have ordered the data.

4. If you have an ORDER BY section and you have more than one AFTERGROUP OF control block, their order within the FORMAT section is notsignificant.

5. When INFORMIX-4GL finishes generating a report, it executes all of thestatements in the AFTER GROUP OF control blocks before it executes thosein 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 OFcontrol block, the variables of the report still have the values from the lastrow of the group. From this perspective, the AFTER GROUP OF controlblock could be called the ‘‘on last row of group’’ control block.

ExamplesAFTER 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_numPRINT 42 SPACES,"---------------"PRINT 42 SPACES,GROUP SUM(r.total_price)USING "$$$$,$$$,$$$.&&"

5-26 Report Writing

Page 315: Manual Informix

BEFORE GROUP OF

BEFORE GROUP OF

OverviewThe BEFORE GROUP OF control block specifies the action that INFORMIX-4GLtakes before it processes a group of rows. Grouping is determined by theordering that you did earlier.

SyntaxBEFORE GROUP OF variable-namestatement. . .

ExplanationBEFORE GROUP OF are required keywords.

variable-name is the name of one of the variables passed as anargument.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. 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 vari-able. INFORMIX-4GL automatically groups rows when you use an ORDERBY section of a REPORT routine or the ORDER clause of a SELECT state-ment. That is, groups are formed when you order a list.

When you specify more than one variable in an ORDER BY section orclause, INFORMIX-4GL orders the rows first by the first variable that youspecify (most significant), second by the second variable, and so on, untilthe last variable that you specify (least significant) is ordered.

INFORMIX-4GL processes the statements in a BEFORE GROUP OF controlblock at the start of a report, each time the specified variable changesvalue, 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 thatyou order.

Report Writing 5-27

Page 316: Manual Informix

BEFORE GROUP OF

4. If you have an ORDER BY section and you have more than one BEFOREGROUP OF control block, their order within the FORMAT section is notsignificant.

5. When INFORMIX-4GL starts to generate a report, it executes all thestatements in the BEFORE GROUP OF control blocks before it executesthose in the ON EVERY ROW control block.

6. You can use a SKIP TO TOP OF PAGE statement in a BEFORE GROUP OFcontrol block to cause each group to start at the top of a page.

7. When INFORMIX-4GL processes the statements in a BEFORE GROUP OFcontrol block, the report variables have the values from the first row of thenew group. From this perspective, the BEFORE GROUP OF control blockcould be called the ‘‘on first row of group’’ control block.

ExampleBEFORE GROUP OF r.customer_num

SKIP TO TOP OF PAGE

5-28 Report Writing

Page 317: Manual Informix

FIRST PAGE HEADER

FIRST PAGE HEADER

OverviewThe FIRST PAGE HEADER control block can specify what information appearsat the top of the first page of the report.

SyntaxFIRST PAGE HEADER

statement. . .

ExplanationFIRST PAGE HEADER are required keywords.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. 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 controlblock on the first page of a report.

3. You cannot use the SKIP TO TOP OF PAGE statement in a FIRST PAGEHEADER control block.

4. If you use an IF THEN ELSE statement in a FIRST PAGE HEADER controlblock, the number of lines displayed by the PRINT statements followingthe THEN keyword must be equal to the number of lines displayed by thePRINT statements following the ELSE keyword.

5. You cannot use the PRINT filename statement to read and display text froma 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

Page 318: Manual Informix

FIRST PAGE HEADER

ExampleThis example is from a report that produces multiple labels across the page.

FIRST PAGE HEADER{Nothing is displayed in this

control block. It justinitializes variables that areused in the ON EVERY ROWcontrol block.}

{Initialize label counter.}LET i = 1

{Determine label width (alloweight spaces total between labels).}

LET l_size = 72/count1

{Divide the eight spaces betweenthe number of labels across the page.}

LET white = 8/count1

This FIRST PAGE HEADER does not display any information. Because INFOR-MIX-4GL executes the FIRST PAGE HEADER control block before it generatesany output, you can use this control block to initialize variables that you usein the FORMAT section.

5-30 Report Writing

Page 319: Manual Informix

ON EVERY ROW

ON EVERY ROW

OverviewThe ON EVERY ROW control block specifies the action to be taken by INFOR-MIX-4GL for every row of data that you pass to the routine.

SyntaxON EVERY ROW

statement. . .

ExplanationON EVERY ROW are required keywords.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. 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 columnvalue, all appropriate BEFORE GROUP OF control blocks are executed (inthe order of their significance) before the ON EVERY ROW control block isexecuted.

3. If an AFTER GROUP OF control block is triggered by a change in columnvalue, all appropriate AFTER GROUP OF control blocks are executed (inthe reverse order of their significance) after the ON EVERY ROW controlblock is executed.

ExamplesThe following example is from a report that lists all the customers, theiraddresses, and their telephone numbers across the page.

ON EVERY ROWPRINT 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

Page 320: Manual Informix

ON EVERY ROW

The next example is from a mailing label report.

ON EVERY ROWIF (city IS NOT NULL) AND

(state IS NOT NULL) THENPRINT fname CLIPPED, 1 SPACE, lnamePRINT companyPRINT address1IF (address2 IS NOT NULL) THEN

PRINT address2PRINT city CLIPPED " , " , state,

2 SPACES, zipcodeSKIP TO TOP OF PAGE

END IF

5-32 Report Writing

Page 321: Manual Informix

ON LAST ROW

ON LAST ROW

OverviewThe ON LAST ROW control block specifies the action that INFORMIX-4GLis to take after it processes the last row passed to the REPORT routine andencounters the FINISH REPORT statement.

SyntaxON LAST ROW

statement. . .

ExplanationON LAST ROW are required keywords.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. INFORMIX-4GL executes the statements in the ON LAST ROW control

block after it executes those in the ON EVERY ROW and AFTER GROUP OFcontrol blocks.

2. When INFORMIX-4GL processes the statements in an ON LAST ROWcontrol block, the columns that the report is processing still have thevalues from the final row that the report processed.

3. The ON LAST ROW control block can display report totals.

ExampleON LAST ROW

SKIP 1 LINEPRINT COLUMN 12, "TOTAL NUMBER OF CUSTOMERS:",

COLUMN 57, COUNT(*) USING " ##"

Report Writing 5-33

Page 322: Manual Informix

PAGE HEADER

PAGE HEADER

OverviewThe PAGE HEADER control block specifies what information (if any) appearsat the top of each page of the report.

SyntaxPAGE HEADER

statement. . .

ExplanationPAGE HEADER are required keywords.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. 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 controlblock on the first page of a report.

3. You cannot use the SKIP TO TOP OF PAGE statement in a PAGE HEADERcontrol block.

4. The number of lines produced by the PAGE HEADER control block cannotchange from page to page, and must be expressed unambiguously. Thefollowing rules are special cases of this general principle:

• You cannot have a SKIP integer LINES statement inside a loop in thePAGE 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 controlblock, the number of lines displayed by the PRINT statementsfollowing the THEN keyword must be equal to the number of linesdisplayed by the PRINT statements following the ELSE keyword.

• If you use a CASE, FOR, or WHILE statement that contains a PRINTstatement in a PAGE HEADER control block, you must terminate theprint statement with a semicolon. The semicolon suppresses RETURNs

5-34 Report Writing

Page 323: Manual Informix

PAGE HEADER

in the loop, keeping the number of lines in the header constant frompage to page.

• You cannot use a PRINT filename statement to read and display textfrom a file in a PAGE HEADER control block.

5. You can use a PAGE HEADER control block to display column headings ina report.

6. You can use the PAGENO expression in a PRINT statement within a PAGEHEADER control block to display the page number automatically at thetop of every page.

ExampleThe following example produces the column headings for printing thecustomer data across the page.

PAGE HEADERPRINT "NUMBER",COLUMN 12, "NAME",COLUMN 35, "LOCATION",COLUMN 57, "ZIP",COLUMN 65, "PHONE"SKIP 1 LINE

Report Writing 5-35

Page 324: Manual Informix

PAGE TRAILER

PAGE TRAILER

OverviewThe PAGE TRAILER control block specifies what information, if any, appearsat the bottom of each page of the report.

SyntaxPAGE TRAILER

statement. . .

ExplanationPAGE TRAILER are required keywords.

statement is an INFORMIX-4GL or FORMAT statement.

Notes1. 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 TRAILERcontrol block.

3. The number of lines produced by the PAGE TRAILER control block cannotchange from page to page and must be unambiguously expressed. Thefollowing rules are special cases of this more general principle:

• You cannot have a SKIP integer LINES statement inside a loop in thePAGE 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 controlblock, the number of lines displayed by the PRINT statements follow-ing the THEN keyword must be equal to the number of lines displayedby the PRINT statements following the ELSE keyword.

• If you use a CASE, FOR, or WHILE statement that contains a PRINTstatement in a PAGE TRAILER control block, you must terminate thePRINT statement with a semicolon. The semicolon suppresses

5-36 Report Writing

Page 325: Manual Informix

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 textfrom a file in a PAGE TRAILER control block.

4. INFORMIX-4GL executes the PAGE TRAILER control block before thePAGE HEADER control block when you issue a SKIP TO TOP OF PAGEstatement anywhere.

5. You can use the PAGENO expression in a PRINT statement within a PAGETRAILER control block to display the page number automatically at thebottom of every page.

ExamplePAGE TRAILER

PRINT COLUMN 28,PAGENO USING "page <<<<"

StatementsThe control blocks determine when INFORMIX-4GL takes an action in areport, while the statements determine what action INFORMIX-4GL takes.You can use any INFORMIX-4GL statement in a control block, as well as anumber of statements that can be used only in the FORMAT section of aREPORT routine.

Standard 4GL Statements

The most common INFORMIX-4GL statements used in the control blocks ofreports are FOR, IF, LET, and WHILE. These statements have the same syntaxthat they have elsewhere in 4GL applications, as described in Chapter 7.(Remember that any local variables referenced in such statements must bespecified 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 aREPORT routine:

NEED PRINT FILEPAUSE SKIPPRINT

Descriptions of these FORMAT section statements follow.

Report Writing 5-37

Page 326: Manual Informix

NEED

NEED

OverviewThis statement causes subsequent display to start on the next page if there isnot the specified number of lines remaining on the current page.

SyntaxNEED num-expr LINES

ExplanationNEED is a required keyword.

num-expr is an expression that evaluates to an integer specifying thenumber of lines needed.

LINES is a required keyword.

Notes1. 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 num-ber of lines counted.

3. If INFORMIX-4GL triggers the NEED statement in printing a report, itprints both the PAGE TRAILER and the PAGE HEADER.

4. You cannot use this statement in PAGE HEADER or PAGE TRAILER controlblocks.

Example NEED 6 LINES

5-38 Report Writing

Page 327: Manual Informix

PAUSE

PAUSE

OverviewThis statement causes output to the terminal to pause until the user pressesRETURN.

SyntaxPAUSE [ "string" ]

ExplanationPAUSE is a required keyword.

string is a quoted message that PAUSE displays. If you do not supply amessage, PAUSE displays no message.

NotesThe PAUSE statement works only if the report goes to the screen. It has noeffect if you include a REPORT TO clause in the OUTPUT section, or a TOclause in the START REPORT statement.

ExampleThe following example causes INFORMIX-4GL to pause while running thereport.

AFTER GROUP OF item_num...

SKIP TO TOP OF PAGEPAUSE "Press RETURN to continue"

Report Writing 5-39

Page 328: Manual Informix

PRINT

PRINT

OverviewThis statement displays information, as specified in the OUTPUT section.

SyntaxPRINT [ exprlist ] [ ; ]

ExplanationPRINT is a required keyword.

exprlist is an optional list of one or more expressions, separated bycommas.

; is an optional symbol that suppresses a RETURN at the end ofthe line.

Notes1. One PRINT statement displays its output on one line, no matter how

many lines the statement occupies in the report specification, unless theexprlist includes the WORDWRAP function.

2. When a PRINT statement specifies WORDWRAP, it can also specify atemporary right margin. The character position of the current columnbecomes the temporary left margin, and the contents of the characterstring are then displayed on as many lines as necessary between thesetemporary margins.

After the PRINT statement with WORDWRAP has executed, any explicitor 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 theirdata type, as shown in Figure 5-2.

5-40 Report Writing

Page 329: Manual Informix

PRINT

Data Type Default Size (in characters)CHAR declared sizeDATE 10DATETIME depends on declared precisionINTERVAL depends on declared precision (including sign)FLOAT 14 (including sign and decimal point)SMALLINT 6 (including sign)INTEGER 11 (including sign)SMALLFLOAT 14 (including sign and decimal point)DECIMAL number of digits plus 2 (including sign and decimal point)SERIAL 11MONEY number of digits plus 3 (including sign, decimal point,

and currency symbol)Figure 5-2 Default Display Widths

ExamplesThe following example is from a mailing label report:

FORMATON EVERY ROW

PRINT fname, lnamePRINT companyPRINT address1PRINT address2PRINT city, " , " , state, 2 SPACES, zipcodeSKIP 2 LINES

The following example is from a report that prints the customer list.

FIRST PAGE HEADERPRINT COLUMN 30, "CUSTOMER LIST"SKIP 2 LINESPRINT "Listings for the State of ", thisstateSKIP 2 LINESPRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION",

COLUMN 57, "ZIP", COLUMN 65, "PHONE"SKIP 1 LINE

PAGE HEADERPRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION",

COLUMN 57, "ZIP", COLUMN 65, "PHONE"SKIP 1 LINE

ON EVERY ROWPRINT 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

Page 330: Manual Informix

PRINT FILE

PRINT FILE

OverviewThis statement displays the contents of a text file in a report.

SyntaxPRINT FILE "filename"

ExplanationPRINT FILE are required keywords.

filename is a required filename that can be a pathname. You must enclosefilename in quotation ( " ) marks.

NoteYou can use the PRINT FILE statement to include the body of a form letter ina report that generates custom letters.

ExamplePRINT FILE "/u/claire/occupant.let"

5-42 Report Writing

Page 331: Manual Informix

SKIP

SKIP

OverviewThis statement skips lines in a report or skips to the top of the next page.

SyntaxSKIP { integer LINE[S] | TO TOP OF PAGE }

ExplanationSKIP is a required keyword.

integer is an integer specifying the number of lines to skip.

LINES is an optional keyword. You can use the keyword LINE inplace of LINES if you like.

TO TOP OF PAGE are optional keywords.

Notes1. 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 PAGEHEADER, PAGE HEADER, or PAGE TRAILER control block.

Report Writing 5-43

Page 332: Manual Informix

Expressions and Built-in Functions

ExamplesThe following example is from a report that prints the customer list.

FIRST PAGE HEADERPRINT COLUMN 30, "CUSTOMER LIST"SKIP 2 LINESPRINT "Listings for the State of ", thisstateSKIP 2 LINESPRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION",

COLUMN 57, "ZIP", COLUMN 65, "PHONE"SKIP 1 LINE

PAGE HEADERPRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION",

COLUMN 57, "ZIP", COLUMN 65, "PHONE"SKIP 1 LINE

ON EVERY ROWPRINT 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.

FORMATON EVERY ROW

IF (city IS NOT NULL) AND (state IS NOT NULL) THENPRINT fname CLIPPED, 1 SPACE, lnamePRINT companyPRINT address1IF (address2 IS NOT NULL) THEN

PRINT address2PRINT city CLIPPED, " , " , state, 2 SPACES, zipcodeSKIP TO TOP OF PAGE

END IF

Expressions and Built-in FunctionsExpressions used within REPORT routines have the same syntax as expres-sions used elsewhere in INFORMIX-4GL. These expressions can include thebuilt-in functions that are described in Chapter 2.

You can also use the 4GL aggregate functions. In REPORT routines, theseaggregates have effects that are slightly different from when they are used ina SELECT statement. The differences are described in the next pages.

5-44 Report Writing

Page 333: Manual Informix

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 rou-tine. (The letter superscripts indicate where their descriptions appear in thismanual.)

ASCIIa MIN()rs

AVG()rs MDY()a

CLIPPEDa MONTH()a

COLUMNa PAGENOr

COUNT(*)rs PERCENT(*)rs

CURRENTa SPACESr

DATEa SUM()rs

DATE()a TIMEa

DAY()a TODAYa

EXTEND()a UNITSa

GROUPr USINGa

LENGTH()a WEEKDAY()a

LINENOr WORDWRAPr

MAX()rs YEAR()a

r You can use these functions only within the FORMAT section of aREPORT routine. A description of these functions follows.

rs You can use these functions only within the FORMAT section of aREPORT routine or in INSERT, SELECT, or UPDATE statements else-where. They are described both in the following pages and inChapter 7.

a These functions are described in Chapter 2.

Report Writing 5-45

Page 334: Manual Informix

Aggregates

Aggregates

OverviewAggregate functions can summarize information in a report.

Syntax[ GROUP ]

{ COUNT ( * ) | PERCENT ( * ) | { SUM | AVG | MIN | MAX } ( expr1 ) }[ WHERE expr2 ]

ExplanationGROUP is an optional keyword that causes the aggregate to reflect

information for a specific group only. You can only use thiskeyword in an AFTER GROUP OF control block.

COUNT ( * ) is a keyword. This keyword is always evaluated as the totalnumber of rows qualified by the optional WHERE clause.

PERCENT ( * ) is the keyword that evaluates COUNT as a percent of the totalnumber of rows in the report.

SUM evaluates as the total of expr1 in the rows qualified by theoptional WHERE clause. SUM ignores rows with NULL valuefor expr1; it returns NULL if all rows have a NULL value forexpr1.

AVG evaluates as the average of expr1 in the rows qualified by theoptional WHERE clause. AVG ignores rows with NULL valuefor expr1; it returns NULL if all rows have a NULL value forexpr1.

MIN evaluates as the minimum of expr1 in the rows qualified bythe optional WHERE clause. MIN ignores rows with NULLvalue for expr1; it returns NULL if all rows have a NULL valuefor expr1.

MAX evaluates as the maximum of expr1 in the rows qualified bythe optional WHERE clause. MAX ignores rows with NULLvalue for expr1; it returns NULL if all rows have a NULL valuefor expr1.

expr1 is the expression that SUM, AVG, MIN, or MAX evaluate. It istypically a numeric variable or a numeric expression thatincludes a numeric variable.

5-46 Report Writing

Page 335: Manual Informix

Aggregates

WHERE is an optional keyword.

expr2 is a Boolean expression that qualifies the aggregate.

NoteThe 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 WHEREclause. See also the section “Boolean Expressions” in Chapter 2.)

ExamplesThis fragment of a REPORT statement uses the AFTER GROUP OF controlblock and GROUP keyword to sum items within each order. The last PRINTstatement calculates the total price of each order, then adds a shippingcharge, and prints the result.

ON EVERY ROWPRINT 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 numberSKIP 1 LINEPRINT 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 LINEPRINT 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 ofevery item in the group comprising the order.

Report Writing 5-47

Page 336: Manual Informix

LINENO

LINENO

OverviewThis expression has the value of the line number of the report line thatINFORMIX-4GL is currently printing.

SyntaxLINENO

ExplanationLINENO is a required keyword.

NoteINFORMIX-4GL computes the current line number by calculating the numberof lines from the top of the page, including the TOP MARGIN.

ExamplePRINT COLUMN 10, LINENO USING "Line <<<"

5-48 Report Writing

Page 337: Manual Informix

PAGENO

PAGENO

OverviewThis expression has the value of the page number of the page that INFOR-MIX-4GL is currently printing.

SyntaxPAGENO

ExplanationPAGENO is a required keyword.

NoteYou can use PAGENO in a PRINT statement in the PAGE HEADER or PAGETRAILER control block to number the pages of a report. (You can also usePAGENO in other control blocks.)

ExamplePAGE TRAILER

PRINT COLUMN 28, PAGENO USING "page <<<<"

Report Writing 5-49

Page 338: Manual Informix

SPACES

SPACES

OverviewThis function returns a string of spaces. It is identical to a quoted stringof spaces.

Syntaxnum-expr SPACE[S]

Explanationnum-expr is a number expression.

SPACES is a required keyword. You can use the keyword SPACE in placeof SPACES if you like.

ExampleThe following example is from a mailing label report.

FORMATON EVERY ROW

PRINT fname, lnamePRINT companyPRINT address1PRINT address2PRINT city, " , " , state, 2 SPACES, zipcodeSKIP 2 LINES

5-50 Report Writing

Page 339: Manual Informix

WORDWRAP

WORDWRAP

OverviewThe WORDWRAP function automatically wraps successive segments of longcharacter strings to the next line of a report. If the string is too long to fit inthe current line, lines are broken between words at temporary left and rightmargins.

Syntaxchar-expr WORDWRAP [ RIGHT MARGIN col ]

Explanationchar-expr is an expression whose value is a character string.

WORDWRAP is a keyword to display long character strings on multiplelines of a report.

RIGHTMARGIN

are optional keywords to specify a temporary right margin.

col is an integer expression, specifying the column number ofthe temporary right margin.

Notes1. The char-expr can include printable ASCII characters, and the TAB

(ASCII 9), NEWLINE (ASCII 10), and RETURN (ASCII 13). A line breakis forced wherever char-expr contains a NEWLINE, a RETURN, or aNEWLINE/ RETURN pair.

2. If you specify WORDWRAP RIGHT MARGIN in a report, the value of coloverrides the specified or default right margin, until all of char-expr hasbeen included in the report.

3. If you do not specify RIGHT MARGIN, the specified or default rightmargin of the report remains in effect.

4. The left margin is the current printing column. The contents of char-exprare displayed on as many lines as necessary between the temporary leftand right margins.

5. When displaying text with WORDWRAP, INFORMIX-4GL starts a new linewhen a word plus the following space will not fit on the current line,

Report Writing 5-51

Page 340: Manual Informix

WORDWRAP

thereby assuring an even left margin when all words are separated by asingle space. When a string of spaces will not fit on a line, INFORMIX-4GLprints enough of the spaces to fill the line, starts a new line, and prints therest of the spaces. INFORMIX-4GL expands a TAB down to enough spacesto reach the next TAB stop. When the next TAB stop is past the right mar-gin, 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 withthe WORDWRAP utility; it will print page footers, page trailers, pagenumbers, and page headers.

ExamplesThe following PRINT statement specifies a left margin in column 10 and atemporary right margin in column 70 to display the character string that isstored 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 segmentsare displayed in successive lines, until the last character of the string isdisplayed.

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

5-52 Report Writing

Page 341: Manual Informix

Chapter

6

4GL FunctionLibraryChapter Overview 3

The 4GL Library Functions 3ARG_VAL 4ARR_COUNT 6ARR_CURR 7DOWNSHIFT 9ERR_GET 10ERR_PRINT 11ERR_QUIT 12ERRORLOG 13INFIELD 14LENGTH 16NUM_ARGS 17SCR_LINE 18SET_COUNT 20SHOWHELP 21STARTLOG 23UPSHIFT 25

Page 342: Manual Informix

6-2 4GL Function Library

Page 343: Manual Informix

Chapter OverviewThis chapter describes the INFORMIX-4GL library functions. You can includeany of these functions in your 4GL source code. The 4GL compiler recognizesthe name of the library function and automatically includes the function inyour final program.

See also the section “Expressions and Built-in Functions” near the end ofChapter 5 for a list of additional functions that you can include in 4GLprograms.

The 4GL Library FunctionsYou cannot include a library function in an SQL statement. You must use theCALL statement to invoke a library function, unless its action returns a singlevalue. The functions marked with an asterisk ( * ) in the following list can onlybe used in CALL statements. The functions listed without an asterisk can beused without CALL in 4GL expressions or in assignment statements.

Function Returned Value or Effectarg_val Command-line argument(s)arr_count Total filled rows of program arrayarr_curr Number of the current row within program arraydownshift Lowers case of uppercase letters in string argumenterr_get Current 4GL error messageerr_print * Prints a 4GL error message on the Error lineerr_quit * Prints a 4GL error message and exitserrorlog * Appends argument to the error loginfield TRUE if argument is the name of the current fieldlength Length in bytes of string argumentnum_args Number of command-line argumentsscr_line Number of the current row within screen arrayset_count * Sets number of rows of program arrayshowhelp * Displays the 4GL HELP Menu and a help messagestartlog * Opens an error log fileupshift Raises case of lowercase letters in string argument

The pages that follow describe these functions in alphabetical order.

Page 344: Manual Informix

ARG_VAL

ARG_VAL

OverviewThe arg_val function returns an argument of the command line that executesyour INFORMIX-4GL application program.

Syntaxarg_val ( expr )

Explanationexpr is an integer expression.

Notes1. 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 toretrieve individual arguments during program execution. The num_argsfunction can determine how many arguments followed the programname on the command line.

The arg_val and num_args functions allow you to pass data to a compiled4GL program from the command line that executes the program.

2. The function arg_val(n) returns the nth command-line argument as aCHAR 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 byarg_val(0) is the name of your 4GL application program.

ExamplesSuppose that your 4GL program called myprog can accept one or more user-names as command-line arguments. Each of the following command linesincludes 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

Page 345: Manual Informix

ARG_VAL

In either case, statements in the following program fragment use the arg_valfunction to store in an array of CHAR variables all the names that the userentered 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 functionreturns the value 4. Executing the LET statements in the FOR loop assigns thefollowing values to elements of the args array:

Variable Valueargs[1] joeargs[2] bobargs[3] sueargs[4] les

Related FunctionNUM_ARGS

4GL Function Library 6-5

Page 346: Manual Informix

ARR_COUNT

ARR_COUNT

OverviewThe arr_count function returns the number of rows that are entered in a pro-gram array during or after an INPUT ARRAY statement.

Syntaxarr_count ( )

NotesYou can use arr_count to record the number of rows that are currently storedin a program array. The arr_count function returns an integer value.

ExampleThe following function uses the value returned by arr_count to set the upperlimit of a FOR statement:

FUNCTION insert_items()DEFINE counter SMALLINTFOR counte r = 1 TO arr_count()

INSERT INTO itemsVALUES (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 FOREND FUNCTION

Related FunctionsARR_CURR, SCR_LINE

6-6 4GL Function Library

Page 347: Manual Informix

ARR_CURR

ARR_CURR

OverviewThe arr_curr function returns the number of the row within the programarray that corresponds to the current screen array row, during or immedi-ately after the INPUT ARRAY or DISPLAY ARRAY statement.

Syntaxarr_curr ( )

Notes1. The current screen row is the row where the cursor is located at the begin-

ning of a BEFORE ROW or AFTER ROW clause.

2. The arr_curr function returns an integer value. The first row of both theprogram array and the screen array is numbered 1.

3. The library functions arr_curr and scr_line can return different values ifthe program array is larger than the screen array.

4GL Function Library 6-7

Page 348: Manual Informix

ARR_CURR

ExampleThe following program segment tests the user input and rejects it if the cus-tomer is not from California. (See also the definition of the scr_line functionlater in this chapter.)

DEFINE p_array ARRAY[90] OF RECORDfname 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 NULLCLEAR scr_array[sc_curr].*NEXT FIELD fname

END IFEND INPUT

Related FunctionsARR_COUNT, SCR_LINE

6-8 4GL Function Library

Page 349: Manual Informix

DOWNSHIFT

DOWNSHIFT

OverviewThe downshift function returns a string value in which all uppercase charac-ters in its argument are converted to lowercase.

Syntaxdownshift ( str )

Explanationstr is a quoted string or a variable of type CHAR.

Notes1. Non-alphabetic characters in str are not altered by downshift.

2. You can use the downshift function in an expression (when such usageis allowed), or you can assign the value returned by the function to avariable.

3. The maximum length of str is 512 characters.

4. See also the DOWNSHIFT field attribute in Chapter 4.

ExampleSuppose that the CHAR value ‘‘GEAR_4’’ is stored in the program variablep_string. The following statement takes the value of the expressiondownshift(p_string), namely gear_4 , and assigns it to another CHAR vari-able called d_str:

LET d_str = downshift(p_string)

Related FunctionUPSHIFT

4GL Function Library 6-9

Page 350: Manual Informix

ERR_GET

ERR_GET

OverviewThe err_get function returns a CHAR string that is the 4GL error message cor-responding to its argument.

Syntaxerr_get ( expr )

Explanationexpr is an integer expression.

Notes1. 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 yourapplication.

ExampleThe LET statement in this segment assigns the text of a 4GL error message toerrtext, a CHAR variable:

IF statu s < 0 THENLET errtext = err_get(status)

END IF

Related FunctionsERR_PRINT, ERR_QUIT, STARTLOG

6-10 4GL Function Library

Page 351: Manual Informix

ERR_PRINT

ERR_PRINT

OverviewThe err_print function displays on the Error line the INFORMIX-4GL errormessage that corresponds to its argument.

SyntaxCALL err_print ( expr )

Explanationexpr is an integer expression.

Notes1. The expr is usually the global status variable.

2. The err_print function is most useful when you are developing a pro-gram. The message that it returns is probably not helpful to the user ofyour application.

ExampleThis program segment sends any error message to the Error line:

IF statu s < 0 THENCALL err_print(status)

END IF

Related FunctionsERR_GET, ERR_QUIT, STARTLOG

4GL Function Library 6-11

Page 352: Manual Informix

ERR_QUIT

ERR_QUIT

OverviewThe err_quit function prints on the Error line the INFORMIX-4GL error mes-sage specified by its argument, and then terminates the program.

SyntaxCALL err_quit ( expr )

ExplanationCALL is a required keyword.

expr is an integer expression.

Notes1. 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 yourapplication.

ExampleIf an error occurs, these statements display the error message on the Errorline, and then terminate program execution:

IF statu s < 0 THENCALL err_quit(status)

END IF

Related FunctionsERR_GET, ERR_PRINT, STARTLOG

6-12 4GL Function Library

Page 353: Manual Informix

ERRORLOG

ERRORLOG

OverviewThe errorlog function writes its argument in the current error log file.

SyntaxCALL errorlog ( str )

ExplanationCALL is a required keyword.

str is a string constant or a CHAR variable.

Notes1. The error log file is created by the startlog function.

2. You can use the errorlog function to identify errors in programs that youare developing and to customize error handling.

ExampleHere the errorlog function has a string constant argument:

CALL startlog("/usr/steve/error.log")...FUNCTION start_menu()CALL errorlog("Entering start_menu function")

Related FunctionSTARTLOG

4GL Function Library 6-13

Page 354: Manual Informix

INFIELD

INFIELD

OverviewThe infield function tests whether its argument is the identifier of the currentscreen field.

Syntaxinfield ( field-name )

Explanationfield-name is the name of a screen field.

Notes1. The infield function is a Boolean function that returns the value true if

field-name is the name of the current screen field. Otherwise infieldreturns the value false . (The “ATTRIBUTES Section” in Chapter 4describes 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 takefield-dependent actions.

3. Outside of an INPUT or INPUT ARRAY statement, infield returns a trueor false value, based on whether field-name corresponds to the screenfield that was current when the user terminated the most recent INPUTor INPUT ARRAY statement. Be sure to specify the field-name, not thefield tag.

4. If the current field is a multiple-column field, infield returns true only iffield-name is the active name.

6-14 4GL Function Library

Page 355: Manual Informix

INFIELD

ExampleThe following INPUT statement uses infield with showhelp to give field-dependent help messages.

INPUT p_rec.* FROM sc_rec.*ON KEY(CONTROL-B)

CASEWHEN infield(field1)

CALL showhelp(101)WHEN infield(field2)

CALL showhelp(102)WHEN infield(field3)

CALL showhelp(103)...

END CASEEND INPUT

Related FunctionSCR_LINE

4GL Function Library 6-15

Page 356: Manual Informix

LENGTH

LENGTH

OverviewThe length function returns the number of bytes in its string argument, afterdeleting all trailing spaces.

Syntaxlength ( str )

Explanationstr is a string constant or a CHAR variable.

NoteIn a SELECT statement, with str the name of a character column, this functionreturns the number of bytes in each CLIPPED value. (This is an exception tothe rule that library functions cannot occur in SQL statements.)

ExamplesThese statements center a report title on an 80-column page:

LET title = "Invoice for ", fname CLIPPED," ", lname CLIPPED

LET offset = (80 - length(title))/2PRINT COLUMN offset, title

The next statement retrieves the value in column1 and the length in bytes ofthe string in column2 (excluding trailing blanks).

SELECT column1, LENGTH(column2) FROM mytable

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFOR-MIX-OnLine Programmer’s Manual for more information.

6-16 4GL Function Library

Page 357: Manual Informix

NUM_ARGS

NUM_ARGS

OverviewThe num_args function returns the number of command-line argumentswith which your INFORMIX-4GL program is run.

Syntaxnum_args ( )

NoteThe num_args function returns an integer, indicating the number of com-mand-line arguments that followed the name of your program when the userinvoked it. (You can use the arg_val library function to retrieve individualarguments.)

ExampleEach of the following command lines includes three arguments:

myprog.4ge kim sue joe (C Compiler Version)fglgo myprog kim sue joe (Rapid Development System)

After either of these command lines, num_args sets 3 as the upper limit of iin 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 FunctionARG_VAL

4GL Function Library 6-17

Page 358: Manual Informix

SCR_LINE

SCR_LINE

OverviewThe scr_line function returns the number of the current screen row within itsscreen array during a DISPLAY ARRAY or INPUT ARRAY statement.

Syntaxscr_line ( )

Notes1. The current screen row is the row where the cursor is located at the begin-

ning of a BEFORE ROW or AFTER ROW clause.

2. The first row of both the program array and of the screen array is num-bered 1.

3. The library functions scr_line and arr_curr can return different values ifthe program array is larger than the screen array.

6-18 4GL Function Library

Page 359: Manual Informix

SCR_LINE

ExampleThe following program segment tests the user input and rejects it if the cus-tomer is not from Alaska. (See also the definition of the arr_curr library func-tion earlier in this chapter.)

DEFINE p_array ARRAY[90] OF RECORDfname 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 NULLCLEAR scr_array[sc_curr].*NEXT FIELD fname

END IFEND INPUT

Related FunctionsARR_COUNT, ARR_CURR

4GL Function Library 6-19

Page 360: Manual Informix

SET_COUNT

SET_COUNT

OverviewThe set_count function tells INFORMIX-4GL the number of filled rows in aprogram array.

SyntaxCALL set_count ( expr )

ExplanationCALL is a required keyword.

expr is an integer expression.

NoteBefore you use an INPUT ARRAY WITHOUT DEFAULTS or a DISPLAY ARRAYstatement, you must call the set_count function with an integer argumentthat specifies the total number of filled rows in the program array. This func-tion supplies an initial value for the arr_count library function to return.

ExampleCALL set_count(23)INPUT ARRAY p_array WITHOUT DEFAULTS

FROM s_array.*

Related FunctionsARR_COUNT, ARR_CURR

6-20 4GL Function Library

Page 361: Manual Informix

SHOWHELP

SHOWHELP

OverviewThe showhelp function displays a help screen. When the user clears the helpscreen, INFORMIX-4GL restores the previous screen.

SyntaxCALL showhelp ( expr )

ExplanationCALL is a required keyword.

expr is an integer expression.

Notes1. 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 helpoptions.

2. If the help message is too long to fit on one screen, a Screen option of theHELP 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 iscleared, and the previous screen is restored.

4. For information on setting up a help file, see the description of themkmessage utility in Appendix E, or the section entitled ‘‘Creating HelpMessages’’ in Chapter 8 of the INFORMIX-4GL User Guide.

4GL Function Library 6-21

Page 362: Manual Informix

SHOWHELP

ExampleThe following example uses infield with showhelp to display field-depen-dent help messages.

INPUT p_rec.* FROM sc_rec.*ON KEY(CONTROL-B)

CASEWHEN infield(field1)

CALL showhelp(101)WHEN infield(field2)

CALL showhelp(102)WHEN infield(field3)

CALL showhelp(103)...

END CASEEND INPUT

Related FunctionINFIELD

6-22 4GL Function Library

Page 363: Manual Informix

STARTLOG

STARTLOG

OverviewThe startlog function opens an error log file.

SyntaxCALL startlog ( filename )

ExplanationCALL is a required keyword.

filename is a quoted string or a CHAR variable that evaluates to the name(or the pathname) of the error log file.

Notes1. 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 areappended to it.

2. If you do not want the error log file to reside in the current directory, youmust specify a full pathname.

3. After you call the startlog function, a record of every subsequent errorthat occurs during the execution of your program is written to the errorlog file.

4. The error record consists of the date, time, source-module name and linenumber, error number, and error message.

5. You can write your own messages in the error log file by using theerrorlog function.

4GL Function Library 6-23

Page 364: Manual Informix

STARTLOG

ExampleIn the following example, a CALL statement invokes the startlog library func-tion, specifying the name of the error log file in a quoted string that includesa pathname and file extension.

...CALL startlog("/usr/steve/error.log")...FUNCTION start_menu()CALL errorlog("Entering start_menu function")...

Related FunctionERRORLOG

6-24 4GL Function Library

Page 365: Manual Informix

UPSHIFT

UPSHIFT

OverviewThe upshift function returns a string in which all lowercase characters in itsargument are converted to uppercase characters.

Syntaxupshift ( str )

Explanationstr is a quoted string or a variable of type CHAR.

Notes1. Non-alphabetic characters in str are not altered.

2. You can use the upshift function in an expression (when such usage isallowed) or in a statement that assigns the value returned by the functionto a program variable.

3. The maximum length of str is 512 characters.

4. See also the UPSHIFT field attribute in Chapter 4.

ExampleHere the CHAR variables u_str and str are equivalent, except that u_str sub-stitutes uppercase letters for any lowercase letters in str.

LET u_str = upshift(str)

DISPLAY u_str

Related FunctionDOWNSHIFT

4GL Function Library 6-25

Page 366: Manual Informix

UPSHIFT

6-26 4GL Function Library

Page 367: Manual Informix

Chapter

7

INFORMIX-4GLStatement SyntaxTypes of Statements 5

Statements Supported Only on INFORMIX-SE 6Statements Supporting INFORMIX-OnLine

Enhancements 7INFORMIX-4GL Extensions to ANSI Syntax 7

SELECT Statement 8DECLARE Statement 9UPDATE Statement 9GRANT Statement 9CREATE TABLE Statement 10CREATE VIEW Statement 10

Definition of Statements 11ALTER INDEX 12ALTER TABLE ( O ) 14BEGIN WORK 18CALL 19CASE 21CLEAR 23CLOSE 25CLOSE DATABASE 27CLOSE FORM 28CLOSE WINDOW 30COMMIT WORK 31CONSTRUCT 32CONTINUE 38CREATE AUDIT 39CREATE DATABASE ( O ) 41CREATE INDEX 44CREATE SYNONYM 47

Page 368: Manual Informix

CREATE TABLE ( O ) 49CREATE VIEW 57CURRENT WINDOW 60DATABASE 62DECLARE 64DEFER 69DEFINE 71DELETE 73DISPLAY 75DISPLAY ARRAY 79DISPLAY FORM 83DROP AUDIT 85DROP DATABASE 86DROP INDEX 88DROP SYNONYM 89DROP TABLE 90DROP VIEW 91ERROR 92EXECUTE 94EXIT 96FETCH 98FINISH REPORT 101FLUSH 102FOR 104FOREACH 106FREE ( O ) 109FUNCTION 110GLOBALS 112GOTO 114GRANT 115IF 118INITIALIZE 120INPUT 122INPUT ARRAY 129INSERT 138LABEL 141LET 142LOAD 143LOCK TABLE 146MAIN 148MENU 149MESSAGE 154OPEN 156

7-2 INFORMIX-4GL Statement Syntax

Page 369: Manual Informix

OPEN FORM 159OPEN WINDOW 160OPTIONS 165OUTPUT TO REPORT 170PREPARE 171PROMPT 173PUT 177RECOVER TABLE 179RENAME COLUMN 181RENAME TABLE 182REPORT 184RETURN 186REVOKE 187ROLLBACK WORK 189ROLLFORWARD DATABASE 190RUN 191SCROLL 192SELECT 193SET EXPLAIN 194SET LOCK MODE ( O ) 197SLEEP 199START DATABASE 200START REPORT 202UNLOAD 203UNLOCK TABLE 205UPDATE 206UPDATE STATISTICS 210VALIDATE 211WHENEVER 213WHILE 216

The SELECT Statement 218SELECT Clause 222INTO Clause 224FROM Clause 226WHERE Clause 228

Comparison Condition 228Join Conditions 234Subquery 237

GROUP BY Clause 240HAVING Clause 242ORDER BY Clause 243INTO TEMP Clause 245UNION Operator 246

INFORMIX-4GL Statement Syntax 7-3

Page 370: Manual Informix

Functions in SQL Statements 248Aggregate Functions 249LENGTH( ) 251DATE( ) 252DAY( ) 253MDY( ) 254MONTH( ) 255WEEKDAY( ) 256YEAR( ) 257CURRENT 258EXTEND( ) 260

7-4 INFORMIX-4GL Statement Syntax

Page 371: Manual Informix

Types of StatementsTwelve types of INFORMIX-4GL statements are available:

• Program Organization Statements

FUNCTION REPORTMAIN

• Variable Definition Statements

DEFINE GLOBALS

• Assignment Statements

INITIALIZE LET

• Program Flow Statements

CALL IFCASE LABELCONTINUE RETURNDEFER RUNEXIT SLEEPFOR WHENEVERFOREACH WHILEGOTO

• Screen Interaction Statements

CLEAR INPUTCLOSE FORM INPUT ARRAYCLOSE WINDOW MENUCONSTRUCT MESSAGECURRENT WINDOW OPEN FORMDISPLAY OPEN WINDOWDISPLAY ARRAY OPTIONSDISPLAY FORM PROMPTERROR SCROLL

• Report Generation Statements

FINISH REPORT START REPORTOUTPUT TO REPORT

INFORMIX-4GL Statement Syntax 7-5

Page 372: Manual Informix

Statements Supported Only on INFORMIX-SE

• Data Definition Statements

ALTER INDEX DROP DATABASEALTER TABLE DROP INDEXCLOSE DATABASE DROP SYNONYMCREATE DATABASE DROP TABLECREATE INDEX DROP VIEWCREATE SYNONYM RENAME COLUMNCREATE TABLE RENAME TABLECREATE VIEW SET EXPLAINDATABASE UPDATE STATISTICS

• Data Manipulation Statements

DELETE SELECTINSERT UNLOADLOAD UPDATE

• Cursor Manipulation Statements

CLOSE OPENDECLARE PUTFETCH SET EXPLAINFLUSH

• Dynamic Management Statements

EXECUTE PREPAREFREE

• Data Access Statements

GRANT SET LOCK MODELOCK TABLE UNLOCK TABLEREVOKE

• Data Integrity Statements

BEGIN WORK ROLLBACK WORKCOMMIT WORK ROLLFORWARD DATABASECREATE AUDIT START DATABASEDROP AUDIT VALIDATERECOVER TABLE

Statements Supported Only on INFORMIX-SEThe following SQL statements are supported only on INFORMIX-SE. Theycannot be used in INFORMIX-OnLine applications.

CREATE AUDITDROP AUDITRECOVER TABLEROLLFORWARD DATABASESTART DATABASE

7-6 INFORMIX-4GL Statement Syntax

Page 373: Manual Informix

Statements Supporting INFORMIX-OnLine Enhancements

Statements Supporting INFORMIX-OnLineEnhancements

The INFORMIX-OnLine database engine recognizes extensions to severalSQL statements. Refer to the INFORMIX-OnLine Programmer’s Manual fordetails of the additional functionality available with INFORMIX-OnLine.

INFORMIX-4GL statements that support INFORMIX-OnLine enhancementsare 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 thestatement.

ALTER TABLE ( O )CREATE DATABASE ( O )CREATE TABLE ( O )FREE ( O )SET LOCK MODE ( O )

INFORMIX-4GL Extensions to ANSI SyntaxRegardless of whether or not your database is MODE ANSI, you can check theSQL statements in your 4GL programs for ANSI compatibility. To check yourprograms at run time, you can set the DBANSIWARN environment variable.To check your programs at compile time, you can set the DBANSIWARN envi-ronment variable or use the -ansi flag when you compile your 4GL source-code files at the system prompt.

Examples:

c4gl -ansi file.4gl -o program.4ge (C Compiler Version)

fglpc -ansi file.4gl (Rapid Development System)

When you compile with the -ansi flag or with the DBANSIWARN environ-ment variable set, SQL statements that include Informix extensions to ANSIsyntax cause warning messages to be written to the .err file. (See Appendix Cfor 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, anyextension to ANSI syntax in an SQL statement causes the charactersSQLAWARN[1] and SQLAWARN[6] to be set to W.

INFORMIX-4GL Statement Syntax 7-7

Page 374: Manual Informix

INFORMIX-4GL Extensions to ANSI Syntax

The following SQL statements generate warnings when Informix extensionchecking is initiated:

ALTER INDEX FLUSHALTER TABLE FREEBEGIN WORK GRANTCLOSE DATABASE LOADCREATE AUDIT LOCK TABLECREATE DATABASE PUTCREATE INDEX RECOVER TABLECREATE SYNONYM RENAME COLUMNCREATE TABLE RENAME TABLECREATE VIEW REVOKEDATABASE ROLLFORWARD DATABASEDROP AUDIT SET EXPLAINDROP DATABASE SET LOCK MODEDROP INDEX START DATABASEDROP SYNONYM UNLOADDROP TABLE UNLOCK TABLEDROP VIEW UPDATE STATISTICS

Note: The BEGIN WORK, LOAD, and UNLOAD statements generate warnings atcompile time only.

The next section lists keywords or features of INFORMIX-4GL that are exten-sions to ANSI standard syntax. A warning is generated if you include thesekeywords or features in an SQL statement, and then initiate Informix exten-sion checking with the -ansi flag or with the DBANSIWARN environmentvariable.

SELECT Statement

The following keywords or features are Informix extensions to the SELECTstatement:

• 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

Page 375: Manual Informix

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 theANSI 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 warningwhen Informix extension checking is initiated. The ANSI standard requiresthat the GRANT statement be issued within the CREATE SCHEMA

INFORMIX-4GL Statement Syntax 7-9

Page 376: Manual Informix

INFORMIX-4GL Extensions to ANSI Syntax

AUTHORIZATION statement. For more information about the CREATESCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQL ReferenceManual.

CREATE TABLE Statement

The following features and keywords are Informix extensions to the CREATETABLE 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 awarning when Informix extension checking is initiated. The ANSI standardrequires that the CREATE TABLE statement be issued within the CREATESCHEMA AUTHORIZATION statement. For more information about theCREATE SCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQLReference Manual.

CREATE VIEW Statement

Use of the CREATE VIEW statement in INFORMIX-4GL always generates awarning when Informix extension checking is initiated. The ANSI standardrequires that the CREATE VIEW statement be issued within the CREATESCHEMA AUTHORIZATION statement. For more information about theCREATE SCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQLReference Manual.

Note: INFORMIX-OnLine supports additional keywords that are extensions. Seethe INFORMIX-OnLine Programmer’s Manual for more information.

7-10 INFORMIX-4GL Statement Syntax

Page 377: Manual Informix

Definition of Statements

Definition of StatementsThe following section describes the INFORMIX-4GL statements. The state-ments appear in alphabetical order. (See also Chapter 5, which describesadditional statements that can only appear in the FORMAT section of aREPORT routine, such as NEED, PAUSE, PRINT, PRINT FILE, and SKIP.)

INFORMIX-4GL Statement Syntax 7-11

Page 378: Manual Informix

ALTER INDEX

ALTER INDEX

OverviewUse the ALTER INDEX statement to cluster a table in the order of an existingindex, or to release an index from the clustering attribute.

SyntaxALTER INDEX index-name TO [ NOT ] CLUSTER

ExplanationALTER INDEX are required keywords.

index-name is the identifier of an existing index.

TO is a required keyword.

NOT is an optional keyword.

CLUSTER is a required keyword.

Notes1. The TO CLUSTER option causes INFORMIX-4GL to reorder the rows in the

physical table to agree with the order of index-name. Reordering causesthe entire file to be rewritten. This process may take a long time andrequires sufficient disk space to maintain two copies of the table. After allrows have been copied to the reordered table, the original version of thetable is automatically deleted, releasing the additional disk space.

2. Since there can be only one clustered index per table, you must use theNOT option to release the cluster attribute from one index before assign-ing it to another. The NOT option does not affect the physical table; itmerely drops the cluster attribute on index-name from the system catalogs.

3. When INFORMIX-4GL executes ALTER INDEX with the TO CLUSTERoption, it locks the table in EXCLUSIVE MODE. If some other process isusing the table to which index-name belongs, INFORMIX-4GL cannot exe-cute ALTER INDEX with the TO CLUSTER option and returns an error.

4. You cannot use a ROLLBACK statement to undo the effect of the ALTERINDEX statement.

7-12 INFORMIX-4GL Statement Syntax

Page 379: Manual Informix

ALTER INDEX

5. As rows are added and deleted, you can expect the benefit of an earlierclustering to disappear. You can recluster the table by issuing anotherALTER INDEX TO CLUSTER statement on the clustered index.

6. You do not need to drop a cluster index before issuing another ALTERINDEX TO CLUSTER statement on a currently clustered index.

ExampleThe following example creates two indexes on the orders table and clustersthe physical table in ascending order on the customer_num column. Later,the example clusters the physical table in ascending order on the order_numcolumn.

CREATE UNIQUE INDEX ix_ordON orders (order_num)

CREATE CLUSTER INDEX ix_custON orders (customer_num)

...

ALTER INDEX ix_cust TO NOT CLUSTER

ALTER INDEX ix_ord TO CLUSTER

Related StatementCREATE INDEX

INFORMIX-4GL Statement Syntax 7-13

Page 380: Manual Informix

ALTER TABLE ( O )

ALTER TABLE ( O )

OverviewUse the ALTER TABLE statement to add a column to a table, delete a columnfrom a table, modify the data type of a column, add a UNIQUE CONSTRAINTto a column or a composite list of columns, or drop a UNIQUE CONSTRAINTassociated with a column or composite list of columns.

SyntaxALTER 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 [ , . . . ] ) } [ , . . . ]

ExplanationALTER TABLE are required keywords.

table-name is the name of an existing table.

ADD is a keyword you use to add a column.

newcol-name is the name of the column you want to add.

newcol-type is either the data type of the column you are adding or thedata type of the column you are modifying.

NOT NULL are optional keywords.

UNIQUE is a keyword specifying that the column or composite col-umn list accepts only unique values.

CONSTRAINT is a keyword you use to indicate that constr-name isassigned in the statement.

constr-name is the name of the constraint.

BEFORE is an optional keyword you use to indicate where youwant newcol-name placed in the list of columns. Thedefault is at the end of the list of columns.

oldcol-name is the name of an existing column.

DROP is a keyword you use to drop a column.

7-14 INFORMIX-4GL Statement Syntax

Page 381: Manual Informix

ALTER TABLE ( O )

MODIFY is a keyword you use to change the data type of an exist-ing column.

ADDCONSTRAINT

are keywords you use to place a constraint on a column orcomposite column list.

DROPCONSTRAINT

are keywords you use to drop a UNIQUE CONSTRAINT ona table column.

Notes1. 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 atable 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 includeit in a statement. See the section “Owner Naming” in Chapter 3 for moreinformation.

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. Usea comma ( , ) to separate clauses. The actions are performed in the orderspecified. 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 col-umn with the CREATE TABLE statement. You cannot add it with theALTER TABLE statement.

4. You can modify an existing column that formerly permitted NULLs to beNOT NULL, provided that it does not already contain any NULL values.Specify MODIFY with the same oldcol-name and data type and the NOTNULL keywords.

5. You can modify an existing column that did not permit NULLs to permitNULLs. Specify MODIFY with the oldcol-name and the existing data typeand omit NOT NULL.

6. When you add a new column to an existing table, it is filled with NULLvalues. Therefore, you cannot use the NOT NULL option or specify aUNIQUE CONSTRAINT when you add a column unless the table containsno data.

7. If you change the data type of an existing column, all data are convertedto the new data type, including number to character and character tonumber (if the characters represent numbers).

When there is a UNIQUE CONSTRAINT, however, conversion takes placeonly if it does not violate the constraint. If a data conversion would resultin duplicate values (by changing FLOAT to SMALLFLOAT, for example, or

INFORMIX-4GL Statement Syntax 7-15

Page 382: Manual Informix

ALTER TABLE ( O )

by truncating CHAR values), then the ALTER TABLE command fails. Youwill receive error 212 (Cannot add index ) and ISAM error 100 (Thereis already a record with the same value in a uniqueindex ).

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 tospecify a UNIQUE CONSTRAINT on a new or existing column, or on acomposite list of columns. The following rules apply when adding aUNIQUE 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 nameof the constraint. If no constr-name name was specified when the con-straint was created, the system generated the name. You can query thesysconstraints system catalog for the names (including the owner) ofconstraints.

11. If you own the table or have alter permission on the table, you can createa constraint on the table and specify yourself as the owner. If you haveDBA permission, you can create constraints for other users.

12. You must own table-name, have DBA privilege, or be granted ALTER per-mission 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 TABLEstatement.

15. The keyword DISTINCT is a synonym for UNIQUE.

7-16 INFORMIX-4GL Statement Syntax

Page 383: Manual Informix

ALTER TABLE ( O )

ExamplesALTER TABLE items

ADD (item_weight DECIMAL(6,2)BEFORE total_price)

ALTER TABLE itemsDROP (total_price)

ALTER TABLE itemsMODIFY (manu_code CHAR(4))

ALTER TABLE manufactADD CONSTRAINT UNIQUE (manu_name) CONSTRAINT con_name

ALTER TABLE manufactDROP CONSTRAINT (con_name)

Since they refer to the same table, you can combine the first two examplesinto a single statement:

ALTER TABLE itemsADD (item_weight DECIMAL(6,2) BEFORE total_price),DROP (total_price)

Related StatementsCREATE TABLE, CREATE INDEX, RENAME COLUMN, RENAME TABLE

INFORMIX-4GL Statement Syntax 7-17

Page 384: Manual Informix

BEGIN WORK

BEGIN WORK

OverviewUse the BEGIN WORK statement to start a transaction (a sequence of databaseoperations that are terminated by the COMMIT WORK or ROLLBACK WORKstatement) in a non-MODE ANSI database. See the section “Transactions” inChapter 3 for a description of transactions.

SyntaxBEGIN WORK

ExplanationBEGIN WORK are keywords to start a transaction.

Notes1. Each row affected by an UPDATE, DELETE, or INSERT statement during a

transaction is locked and remains locked throughout the transaction. Atransaction that contains a large number of such statements, or that con-tains statements affecting a large number of rows, may exceed the limitsplaced by your operating system on the maximum number of simulta-neous locks. If you encounter this error, you may need to lock the entiretable immediately after beginning the transaction. See the section “Lock-ing” in Chapter 3 for a more detailed description of table-level and row-level locking in INFORMIX-4GL.

2. Do not use the BEGIN WORK statement with a database CREATEd orSTARTed as MODE ANSI. In a program that accesses a MODE ANSI data-base, the BEGIN WORK statement generates a run-time error unless itappears immediately after one of the following statements:

CREATE DATABASE COMMIT WORKDATABASE ROLLBACK WORKSTART DATABASE

3. See the “Transactions” section in Chapter 3 for a full description oftransactions.

Related StatementsCOMMIT WORK, ROLLBACK WORK

7-18 INFORMIX-4GL Statement Syntax

Page 385: Manual Informix

CALL

CALL

OverviewUse the CALL statement to invoke a function.

SyntaxCALL function ( [ argument-list ] ) [ RETURNING variable-list ]

ExplanationCALL is a required keyword.

function is the name of a function.

argument-list is a list of zero or more expressions, separated by commasand enclosed in parentheses, that are passed to the function.The parentheses are required, even if there are noarguments.

RETURNING is an optional keyword to specify variables that the functionwill return to the calling routine.

variable-list is a list of one or more program variables, separated bycommas.

Notes1. 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 usingsuch 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 theMAIN program block, or you can compile them separately and link themlater to the MAIN program block.

ExampleCALL statistics(rec.*) RETURNING mean, std_dev

INFORMIX-4GL Statement Syntax 7-19

Page 386: Manual Informix

CALL

Related StatementsDEFINE, FUNCTION

7-20 INFORMIX-4GL Statement Syntax

Page 387: Manual Informix

CASE

CASE

OverviewUse the CASE statement to select a sequence of statements, depending on thecurrent value of an expression.

SyntaxCASE [ ( expr ) ]

WHEN { expr | Boolean-expr }statement. . .[ EXIT CASE ]...

WHEN { expr | Boolean-expr }statement. . .[ EXIT CASE ]. . .

...[ OTHERWISE ]

statement. . .[ EXIT CASE ]. . .

END CASE

ExplanationCASE is a required keyword.

expr is an expression that returns an INTEGER, SMALLINT,DECIMAL, or CHAR(1) value.

WHEN is a required keyword.

Boolean-expr is an expression that is either TRUE or FALSE.

statement is an INFORMIX-4GL statement.

EXIT CASE is an optional statement that causes program control to passto the statement following the END CASE keywords.

OTHERWISE is an optional keyword introducing a sequence of statementsto be executed if none of the WHEN clauses is executed.

END CASE are required keywords that terminate the CASE statement.

INFORMIX-4GL Statement Syntax 7-21

Page 388: Manual Informix

CASE

Notes1. 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 ismissing, you must follow the WHEN keyword with a Boolean expression.If there is an expression following the CASE keyword, you must followthe WHEN keyword with an expression that evaluates to the same datatype.

4. There is an implied EXIT CASE statement at the end of each sequence ofstatements following a WHEN clause. Program control will pass to thesequence of statements following the END CASE statement.

ExampleLABEL question:

...CASE

WHEN answer MATCHES "[Yy]"CALL process()

WHEN answer MATCHES "[Nn]"CALL abort()

OTHERWISECALL retry()

END CASE

Related StatementsIF, EXIT

7-22 INFORMIX-4GL Statement Syntax

Page 389: Manual Informix

CLEAR

CLEAR

OverviewUse the CLEAR statement to clear the whole screen, a window, all fields in ascreen form, or a set of fields.

SyntaxCLEAR { SCREEN | WINDOW window-name | FORM | field-list }

ExplanationCLEAR is a required keyword.

SCREEN is the keyword to clear the whole screen.

WINDOW is the keyword to clear a window.

window-name is the name of the window that you want to clear, or the key-word SCREEN.

FORM is the keyword to clear the values in all screen fields of aform.

field-list is a list of one or more names of fields to be cleared.

Notes1. 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 andclears it.

3. The CLEAR WINDOW statement clears the specified window, retainingany border. (The specified window need not be the current window. Thisoption does not affect which window is the current window.)

4. If you specify SCREEN as the window-name in a CLEAR WINDOW state-ment, INFORMIX-4GL clears the screen, except for the area occupied byany open windows.

5. CLEAR FORM and CLEAR field-list apply to the form in the currentwindow.

INFORMIX-4GL Statement Syntax 7-23

Page 390: Manual Informix

CLEAR

ExamplesCLEAR fname, lname, address1,

city, state, zipcode

CLEAR FORM

CLEAR SCREEN

CLEAR WINDOW win1

CLEAR WINDOW SCREEN

7-24 INFORMIX-4GL Statement Syntax

Page 391: Manual Informix

CLOSE

CLOSE

OverviewUse the CLOSE statement when you no longer need to refer to the active setof a SELECT cursor, or when you want to flush the insert buffer and close anINSERT cursor.

SyntaxCLOSE cursor-name

ExplanationCLOSE is a required keyword.

cursor-name is the name of a cursor that has been DECLAREd for a SELECTor INSERT statement.

Notes1. 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 statementuntil you reopen the cursor.

3. If cursor-name is associated with an INSERT statement, the CLOSE state-ment flushes any rows in the buffer into the database (writes to disk) andcloses the cursor.

4. After you CLOSE an INSERT cursor, you cannot execute a PUT or FLUSHstatement until after you use an OPEN command to reopen the cursor.

5. The global variables status (whose value is taken from the SQLCA.SQL-CODE ) and SQLCA. SQLERRD [3] indicate the result of each FLUSH andCLOSE statement for an INSERT cursor. If INFORMIX-4GL successfullyinserts the buffered rows into the database, it sets status to zero, andSQLCA. SQLERRD [3] to the number of rows that were inserted into thedatabase.

If INFORMIX-4GL encounters an error while inserting the buffered rowsinto the database, it sets status to a negative number (specifically, thenumber of the error message) and sets variable SQLCA. SQLERRD [3] to thenumber of rows successfully inserted into the database. Any buffered

INFORMIX-4GL Statement Syntax 7-25

Page 392: Manual Informix

CLOSE

rows following the last successfully inserted row are discarded. In thiscase, the cursor remains open.

6. Although the COMMIT WORK and ROLLBACK WORK statements CLOSEall open cursors (except cursors declared WITH HOLD ), do not use themfor this purpose. You should explicitly CLOSE each INSERT cursor beforecommitting the work, so that you can verify that the insertion wassuccessful.

7. INFORMIX-4GL does not provide a global variable containing the totalnumber of rows successfully inserted into the database with an INSERTcursor. If you want to know the total number of inserts performed, youmust set a counter in your program and increment it upon each PUTstatement.

8. If your database is not MODE ANSI but has transactions, you must issuethe CLOSE statement within a transaction.

ExamplesCLOSE query_cursor

CLOSE icurs

Related StatementsDECLARE, FETCH, FLUSH, OPEN, PUT

7-26 INFORMIX-4GL Statement Syntax

Page 393: Manual Informix

CLOSE DATABASE

CLOSE DATABASE

OverviewUse the CLOSE DATABASE statement to close the current database.

SyntaxCLOSE DATABASE

ExplanationCLOSE DATABASE are required keywords.

Notes1. Following the CLOSE DATABASE statement, the only legal SQL statements

are CREATE DATABASE, DATABASE, DROP DATABASE, ROLLFORWARDDATABASE, and START DATABASE.

2. Issue the CLOSE DATABASE statement before you DROP the currentdatabase.

3. The CLOSE DATABASE statement cannot appear in a multi-statementPREPARE.

ExampleCLOSE DATABASE

Related StatementsCREATE DATABASE, DROP DATABASE, ROLLFORWARD DATABASE,START DATABASE

INFORMIX-4GL Statement Syntax 7-27

Page 394: Manual Informix

CLOSE FORM

CLOSE FORM

OverviewUse the CLOSE FORM statement to release the memory required for a screenform.

SyntaxCLOSE FORM form-name

ExplanationCLOSE FORM are required keywords.

form-name is an INFORMIX-4GL identifier that you assigned to a screenform in an OPEN FORM statement.

Notes1. After you execute the CLOSE FORM statement, form-name is no longer

associated with a screen form. Executing a subsequent DISPLAY FORMstatement 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 isloaded into memory, where it remains until you execute a CLOSE FORMstatement for that form. If you have displayed another form and wish toregain the memory allocated to the first form, you can execute CLOSEFORM on the old form.

4. The CLOSE FORM statement affects memory use only and does not affectthe logic of the program. Since allocating memory and reading a formfrom the disk takes time, you should leave forms open that you userepeatedly.

5. The CLOSE WINDOW statement closes any open form in the specifiedwindow, releasing the memory allocated to that form.

ExampleCLOSE FORM order_entry

7-28 INFORMIX-4GL Statement Syntax

Page 395: Manual Informix

CLOSE FORM

Related StatementsCLOSE WINDOW, DISPLAY FORM, FREE, OPEN FORM

INFORMIX-4GL Statement Syntax 7-29

Page 396: Manual Informix

CLOSE WINDOW

CLOSE WINDOW

OverviewUse the CLOSE WINDOW statement to close a window.

SyntaxCLOSE WINDOW window-name

ExplanationCLOSE WINDOW are required keywords.

window-name is the name of the window to be closed.

Notes1. 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 stackbecomes the current window. When you close any other window, INFOR-MIX-4GL simply removes the window from the stack, leaving the currentwindow unchanged. In both cases, INFORMIX-4GL restores the underly-ing display.

3. If you close a window that is currently being used for input, INFOR-MIX-4GL generates a run-time error. For example, closing the currentwindow in the middle of a DISPLAY ARRAY, INPUT, INPUT ARRAY, orMENU statement produes a run-time error.

4. You cannot issue a CLOSE WINDOW screen command.

ExampleCLOSE WINDOW win 1

Related StatementsCLEAR WINDOW, CURRENT WINDOW, OPEN WINDOW, OPTIONS

7-30 INFORMIX-4GL Statement Syntax

Page 397: Manual Informix

COMMIT WORK

COMMIT WORK

OverviewUse the COMMIT WORK statement to commit all modifications made to thedatabase during a transaction.

SyntaxCOMMIT WORK

ExplanationCOMMIT WORK are required keywords.

Notes1. Use the COMMIT WORK statement when you are satisfied with all

changes made during the transaction to the database. Use the ROLLBACKWORK statement if you do not want to commit modifications made dur-ing the transaction to the database.

2. The COMMIT WORK statement closes all open cursors, except cursorsdeclared WITH HOLD. Do not use the COMMIT WORK statement within aFOREACH 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 theCOMMIT WORK statement works.

Related StatementsBEGIN WORK, ROLLBACK WORK

INFORMIX-4GL Statement Syntax 7-31

Page 398: Manual Informix

CONSTRUCT

CONSTRUCT

OverviewUse the CONSTRUCT statement to create a CHAR variable that contains theBoolean expression constructed from a screen-generated query by example.The resulting CHAR variable contains conditions for the WHERE clause of aSELECT statement, corresponding to user-specified selection criteria.

SyntaxCONSTRUCT

{ BY NAME char-variable ON column-list |char-variable ON column-list FROM

{ field-list | screen-record [ [ n ] ].* } [ , . . . ] }[ ATTRIBUTE ( attribute-list) ]

ExplanationCONSTRUCT is a required keyword.

BY NAME are keywords instructing INFORMIX-4GL to match names ofdatabase columns to screen field names.

char-variable is an identifier of a CHAR type program variable (to containthe selection criteria).

ON is a required keyword to specify database columns.

column-list is a list of one or more database column names, separated bycommas. You can use the syntax table.*.

FROM is a keyword to specify screen fields for user entry of searchvalues, and for display of query results.

field-list is a list of one or more screen field names.

screen-record is the identifier of a collection of field names defined in aform specification as a screen record.

[ n ] is an integer or integer variable, enclosed in brackets, tospecify the row in a screen array in which the CONSTRUCTtakes place.

ATTRIBUTE is a keyword to specify screen display attributes.

(attribute-list) is a list (in parentheses) of one or more screen displayattributes, separated by commas.

7-32 INFORMIX-4GL Statement Syntax

Page 399: Manual Informix

CONSTRUCT

Notes1. The CONSTRUCT statement allows the user to enter query-by-example

search parameters in a screen form, with this syntax:

Symbol Name Data Types Pattern= equal to all =x> greater than all >x< less than all <x>= greater than or equal to all >=x<= less than or equal to all <=x<> not equal to all <>x: range all x:y. . range DATETIME x..y

andINTERVAL

* wildcard for any string CHAR *x, x*, *x*? single-character wildcard CHAR ?x, x?, ?x?, x??| or all a|b...

Explanation of Symbols

• The equal sign ( = ) is the default query symbol for non-character col-umns, and for character columns in which the user enters a searchvalue 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 con-tains a NULL column. Enter = * to find a row that contains a columnwith 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 sym-bols in the preceding table. Do not leave a space between the querysymbol and the value.

• The symbols >, <, > =, and < = imply an ordering of the data in the col-umn. For CHAR data, ‘‘greater than’’ means later in the ASCII collating

INFORMIX-4GL Statement Syntax 7-33

Page 400: Manual Informix

CONSTRUCT

sequence (where a < A < 1 ), as listed in Appendix H. For DATE andDATETIME data, ‘‘greater than’’ means after.

• Colon in x : y searches for all values between x and y, inclusive. Herevalue y must be larger than x. The search criterion 1 : 10 would findall rows with a value in that column from 1 through 10 .

• Substitute two periods ( . . ) for the colon in DATETIME and INTERVALranges to avoid ambiguity with the field separator in hh: mi: ss values.

• Asterisk ( * ) is the string wildcard, representing zero or more charac-ters. An *ts* search value in the field corresponding to the lnamecolumn of the customer table would find two names, Watson andAlbertson. An S* search value in the same field would find Sadler andSipes. An *er search value would find the four names Sadler, Miller,Jaeger, and Baxter.

• The question mark ( ? ) is the single-character wildcard. The user canuse the question mark to find values that match a pattern where thenumber of characters is fixed. For example, the user can enterEriks?n to search for names like ‘‘Erikson’’ and ‘‘Eriksen.’’ Similarly,the user can enter New??n to search for names like ‘‘Newton,’’ ‘‘New-man,’’ and ‘‘Newson.’’

• The symbo| between values a and b means the logical OR. In the fieldcorresponding to the column customer_num, this entry retrieves anyof three numbers: 102|105|118

2. You can use the BY NAME option when the field names on the screen formhave 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 explic-itly in field-list.

3. The CONSTRUCT statement is terminated when the user enters ESC or thekey specified as the Accept key in the OPTIONS statement. For single-itemCONSTRUCTs, pressing RETURN is equivalent to pressing the Accept key,unless the INPUT WRAP option is in effect. For multiple-item CON-STRUCTs, a RETURN after the last item is equivalent to pressing the Acceptkey, unless INPUT WRAP is in effect.

4. By default, both ESC and Interrupt exit from CONSTRUCT statements. Ifthe DEFER INTERRUPT statement has been executed, an Interrupt sets theglobal variable int_flag to nonzero and terminates the CONSTRUCT state-ment (but not the 4GL program). Otherwise, an Interrupt causes animmediate program stop.

7-34 INFORMIX-4GL Statement Syntax

Page 401: Manual Informix

CONSTRUCT

5. In addition to the RETURN, ESC, ARROW, and Interrupt keys, the user canemploy the following keys for editing during a CONSTRUCT statement:

CTRL-A toggles between insert and typeover mode.

CTRL-D deletes characters from the current cursor position to the endof the field.

CTRL-H moves the cursor nondestructively one space to the leftinside a field. It is equivalent to pressing the [←] key.

CTRL-L moves the cursor nondestructively one space to the rightinside a field. It is equivalent to pressing the [→] key.

CTRL-R redisplays the screen.

CTRL-X deletes the character beneath the cursor.

6. The user can query for only those fields displayed on the screen that youhave specified in the FROM clause or implied in the BY NAME clause. Thenumber of fields in the FROM clause must be the same as the number ofcolumns in the ON clause. The order of fields in the FROM clause mustmatch the order of columns in the ON clause. INFORMIX-4GL constructschar-variable by associating the column name in the ON clause with thesearch condition that the user entered into the corresponding field in theFROM clause.

7. The UPSHIFT and DOWNSHIFT attributes work during a CONSTRUCTstatement. The COMMENTS attribute works, but with the followingrestriction: if a field that displays a comment is too short to hold thesearch criteria that the user enters, INFORMIX-4GL opens a work space onthe Comment line, erasing any comment that is displayed.

8. If the column names in a CONSTRUCT BY NAME statement are associatedwith field names in a screen array, the construct takes place in the first rowof the screen array.

If you want to use screen-array field names in the FROM clause of aCONSTRUCT 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 ofa 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 col-umn names include an owner name. You must use the FROM clause tospecify table aliases in the field-list when any column names contain anowner name.

INFORMIX-4GL Statement Syntax 7-35

Page 402: Manual Informix

CONSTRUCT

11. When you use screen-record.* or table.* as shorthands for explicit lists, besure that the order of the fields implied in the screen-record.* notation cor-responds to the order of the columns implied in the screen-record.*notation. The order of the fields in screen-record.* depends on its definitionin the screen form.

The order of the columns in table.* depends on the order in the syscol-umns system catalog at the time you compile your program. If you haveused ALTER TABLE to change the order or number of the columns in tablesince you compiled your program, you may need to modify your pro-gram and the forms that depend on it.

12. Any screen attributes specified in attribute-list apply to all the fields infield-list or screen-record.

13. If you use the ATTRIBUTE clause, none of the default attributes listed insyscolatt or in the form specification file for fields in field-list or screen-record apply. The attribute-list temporarily overrides any attributes speci-fied in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement forthese fields.

14. These keywords can appear in the ATTRIBUTE clause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

You can specify zero or one of the keywords in the left-hand columns, andfrom zero to three from the right-hand column (but some terminals maynot support some combinations). On color terminals, NORMAL is inter-preted 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 onmonochrome terminals of keywords that specify color.

These keywords cannot produce the effects indicated unless the termcapor terminfo files and the physical terminals support the attribute. (SeeAppendix I, “Modifying termcap and terminfo.”’)

15. On UNIX systems that use terminfo files rather than termcap, INFOR-MIX-4GL does not support attributes that specify colors, and the onlyvalid attribute-list keywords are REVERSE and UNDERLINE.

16. You must first execute OPEN FORM or OPEN WINDOW WITH FORM beforeyou can use the CONSTRUCT statement.

7-36 INFORMIX-4GL Statement Syntax

Page 403: Manual Informix

CONSTRUCT

ExampleThe following program fragment illustrates the use of the CONSTRUCT state-ment to specify the search condition of a WHERE clause. The cursor_1 cursoris DECLAREd and used to execute the query.

CONSTRUCT query_1ON order_num, customer_num, order_date,

ship_dateFROM order_num, customer_num, order_date,

ship_dateATTRIBUTE(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 StatementsDECLARE, PREPARE, OPEN FORM, OPTIONS, SELECT

INFORMIX-4GL Statement Syntax 7-37

Page 404: Manual Informix

CONTINUE

CONTINUE

OverviewUse the CONTINUE statement to cause a FOR, FOREACH, or WHILE statementto start a new cycle immediately, if the conditions permit, or to return to themenu from an option in the MENU statement.

SyntaxCONTINUE { FOR | FOREACH | MENU | WHILE }

ExplanationCONTINUE is a required keyword.

FOR is a required keyword in a FOR statement.

FOREACH is a required keyword in a FOREACH statement.

MENU is a required keyword in a MENU statement.

WHILE is a required keyword in a WHILE statement.

Related StatementsEND, EXIT

7-38 INFORMIX-4GL Statement Syntax

Page 405: Manual Informix

CREATE AUDIT

CREATE AUDIT

OverviewUse the CREATE AUDIT statement to create an audit trail file, and to start writ-ing the audit trail.

SyntaxCREATE AUDIT FOR table-name IN "pathname"

ExplanationCREATEAUDIT FOR

are required keywords.

table-name is the name of the table for which to create an audit trail file.

IN is a required keyword.

pathname is the full pathname for the audit trail file. It must beenclosed in quotation ( " ) marks.

Notes1. 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 tothe table. INFORMIX-4GL can use the audit trail to reconstruct the tablefrom a backup copy made at the time the audit trail is created. (See theRECOVER TABLE statement.) See the section “Audit Trails” in Chapter 3for more information.

2. If an audit trail file with the same pathname already exists for the sametable, the CREATE AUDIT statement does nothing. If an audit trail file forthe same table exists with a different pathname, INFORMIX-4GL displaysan error message.

3. Make a backup copy of your database files as soon as you run the CREATEAUDIT statement, but before you make any further changes to the data-base. (See the RECOVER TABLE statement for an example.) If possible,put the audit trail file on a different physical device from the one thatholds your data, so that a failure of one does not damage the data on theother.

4. Audit trails slow INFORMIX-4GL slightly because each alteration of thetable is recorded in the audit trail file, as well as in the database files.

INFORMIX-4GL Statement Syntax 7-39

Page 406: Manual Informix

CREATE AUDIT

5. You must own table-name or have DBA status to use the CREATE AUDITstatement.

6. You must set execute permission for all directories below root in pathnamefor each class of user (owner, owner’s group, and public) that accessesyour 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.

ExampleCREATE AUDIT FOR orders IN "/dbdir/safe"

Related StatementsDROP AUDIT, RECOVER TABLE

7-40 INFORMIX-4GL Statement Syntax

Page 407: Manual Informix

CREATE DATABASE ( O )

CREATE DATABASE ( O )

OverviewUse the CREATE DATABASE statement to create a new database. INFOR-MIX-4GL will create the system catalogs that will contain the data dictionarydescribing the structure of the database. The database that you create auto-matically becomes the current database.

SyntaxCREATE DATABASE database-name

[ WITH LOG IN "pathname" [ MODE ANSI ] ]

ExplanationCREATEDATABASE

are required keywords.

database-name is the name that you assign to the database. The database-name can be a program variable of type CHAR containing thename of the database you want to create.

WITH LOG IN are optional keywords to support transactions.

pathname is the full pathname, enclosed in quotation ( " ) marks, of thetransaction log file.

MODE ANSI are optional keywords that specify the database as MODEANSI.

Notes1. INFORMIX-4GL creates a subdirectory in the current directory with the

name database-name.dbs. All of the system catalogs, data, and index fileswill be placed in this subdirectory, except for tables that you explicitlyinstruct INFORMIX-4GL to create elsewhere.

2. A database name can be up to 10 characters long and can contain only let-ters, digits, and underscores ( _ ). The first character must be a letter. If youstore more than one database in a single directory, the database namesmust be unique.

INFORMIX-4GL Statement Syntax 7-41

Page 408: Manual Informix

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 data-base-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 ROLLBACKWORK statements. You can use the START DATABASE statement to assigna log file to an existing database. See the section “Transactions” inChapter 3 for further details.

You must include the WITH LOG IN keywords and specify a transactionlog file when you use the MODE ANSI keywords in the CREATEDATABASE statement.

6. A database created as MODE ANSI supports implicit transactions. Allstatements automatically appear within a transaction. (Do not use theBEGIN WORK statement in a program that accesses a MODE ANSI data-base.) You explicitly terminate a transaction when you issue a COMMITWORK or ROLLBACK WORK statement.

7. You can determine the type of database that a user selects by checking thewarning flag after a DATABASE statement in the SQLCA.SQLAWARNstructure. See the section “SQLCA Record” in Chapter 3 for more infor-mation about the SQLCA.SQLAWARN character string.

8. You cannot drop MODE ANSI from a database. Once created or started assuch, a database remains MODE ANSI.

9. The CREATE DATABASE statement cannot appear in a multi-statementPREPARE.

ExamplesThis CREATE DATABASE statement creates the stores database with a trans-action log file:

CREATE DATABASE storesWITH LOG IN "/s/log/stores.log"

This CREATE DATABASE statement creates the stores database as MODEANSI:

CREATE DATABASE storesWITH LOG IN "/u/myname/stores.log" MODE ANSI

7-42 INFORMIX-4GL Statement Syntax

Page 409: Manual Informix

CREATE DATABASE ( O )

Related StatementsDROP DATABASE, GRANT, START DATABASE

INFORMIX-4GL Statement Syntax 7-43

Page 410: Manual Informix

CREATE INDEX

CREATE INDEX

OverviewUse the CREATE INDEX statement to create an index for one or more columnsin 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 columnsis treated as a single composite column for indexing.

SyntaxCREATE [ UNIQUE ] [ CLUSTER ] INDEX index-name

ON table-name ( column-name [ ASC | DESC ] [ , . . . ] )

ExplanationCREATE INDEX are required keywords.

UNIQUE is a keyword to prevent duplicate entries in the column orcomposite column to which the index applies.

CLUSTER is an optional keyword that causes the physical table to beordered according to the order of the index.

index-name is the SQL identifier you want to assign to the index. Youmust assign a different identifier to each index in thedatabase.

ON is a required keyword.

table-name is the name of the table containing the column or columnsthat you want to index.

column-name is the name of a column to be indexed. To create an indexthat applies to several columns, enter a list of column names,separated by commas. All the columns must belong to thesame table.

ASC is a keyword that specifies an index that INFORMIX-4GLmaintains in ascending order. ASC is the default.

DESC is a keyword that specifies an index that INFORMIX-4GLmaintains in descending order.

7-44 INFORMIX-4GL Statement Syntax

Page 411: Manual Informix

CREATE INDEX

Notes1. 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 state-ment cannot exceed 120 bytes.

4. See the section “Indexing Strategy” in Chapter 3 for a discussion of index-ing strategy.

5. The CREATE CLUSTER INDEX statement fails if a CLUSTER index alreadyexists.

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 INDEXstatement.

9. When you create a table, you can specify that a column or composite col-umn will allow only unique values. You use the UNIQUE keyword in theCREATE TABLE statement.

10. You cannot create an ascending index on a column defined as UNIQUE ina CREATE TABLE statement.

11. A column list defined as having a UNIQUE CONSTRAINT in a CREATETABLE statement receives a unique ascending composite index. You can-not use the CREATE INDEX statement to create an identical uniquecomposite index.

12. In a composite index, you can include a column defined as UNIQUE. Sim-ilarly, in a composite index you can include a composite column listdefined as UNIQUE. However, the column list in the CREATE INDEX state-ment cannot be identical to the column list defined as UNIQUE in theCREATE TABLE statement.

13. When more than one column is listed, the concatenation of the set of col-umns 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

Page 412: Manual Informix

CREATE INDEX

ExamplesCREATE UNIQUE INDEX i_ordnum

ON orders (order_num)

CREATE CLUSTER INDEX i_ordnum2ON orders (order_num DESC)

Related StatementsALTER INDEX, CREATE TABLE, DROP INDEX

7-46 INFORMIX-4GL Statement Syntax

Page 413: Manual Informix

CREATE SYNONYM

CREATE SYNONYM

OverviewUse the CREATE SYNONYM statement to provide an alternative name for atable or view.

SyntaxCREATE SYNONYM synonym FOR table-name

ExplanationCREATE SYNONYM are required keywords.

synonym is an SQL identifier.

FOR is a required keyword.

table-name is the name of a table or view.

Notes1. In a MODE ANSI database, the name of a synonym is qualified by the

owner of the synonym (owner. synonym). You must specify owner whenyou 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 includeit in a statement. See the section “Owner Naming” in Chapter 3 of thismanual.

2. A user has no privileges under a synonym that were not granted for thetable to which it applies.

3. When a synonym is created in an INFORMIX-4GL program, the owner ofthe 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 state-ment. 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 beunique among all the synonyms, tables, and views in the database. In anon-MODE ANSI database, synonym must be unique.

INFORMIX-4GL Statement Syntax 7-47

Page 414: Manual Informix

CREATE SYNONYM

ExampleCREATE SYNONYM cust FOR customer

Related StatementsDROP SYNONYM, SELECT

Note: Synonyms are very useful for referencing external objects with INFOR-MIX-OnLine. Refer to the INFORMIX-OnLine Programmer’s Manual for moreinformation.

7-48 INFORMIX-4GL Statement Syntax

Page 415: Manual Informix

CREATE TABLE ( O )

CREATE TABLE ( O )

OverviewUse the CREATE TABLE statement to create a new table in the currentdatabase.

SyntaxCREATE [ 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 ]

ExplanationCREATE TABLE are required keywords.

TEMP is an optional keyword.

table-name is the SQL identifier that you assign to the table. The firstten characters must be unique within a database.

column-name is the SQL identifier that you assign to each column.

datatype specifies the data type for each column. (See the followinglist for valid SQL data types.)

NOT NULL are optional keywords to prevent entry of NULL values.

UNIQUE is an optional keyword specifying that the column orcomposite unique-col-list cannot contain duplicate values.

(unique-col-list) is a list (in parentheses) of the names of columns toinclude in a composite UNIQUE CONSTRAINT.

CONSTRAINT is a keyword to indicate that constr-name is assigned in thestatement.

constr-name is the name of the UNIQUE CONSTRAINT. A constr-namemust be a valid identifier that does not conflict with anexisting constraint name. It can be optionally prefixedwith the username of the owner of the table or, if you haveDBA privileges, the username of another user.

INFORMIX-4GL Statement Syntax 7-49

Page 416: Manual Informix

CREATE TABLE ( O )

WITH NO LOG are optional keywords that prevent logging of TEMPtables. In a database that uses logging, the default is to logTEMP tables also.

IN is an optional keyword.

pathname specifies the full pathname in which to store the databasetable, with no extension to the filename. A pathname can-not be longer than 64 characters and must be enclosedwithin quotes ( " ). A pathname is of the form:

[ /directory-name/ . . . ] filename

A list of valid SQL data types follows:

CHAR ( n ) is a character string of length n (where 1 ≤ n ≤ 32,511).

CHARACTER is a synonym for CHAR.

SMALLINT is a whole number from -32,767 to +32,767.

INTEGER is a whole number from -2,147,483,647 to +2,147,483,647.

INT is a synonym for INTEGER.

DECIMAL [(m[,n])] is a decimal floating-point number with a total of m (≤ 32)significant digits (precision) and n (≤ m) digits to the rightof the decimal point (scale). See the section “DatabaseData Types” in Chapter 3 for more information.

DEC is a synonym for DECIMAL.

NUMERIC is a synonym for DECIMAL.

SMALLFLOAT is a binary floating-point number corresponding to the‘‘float’’ data type in the C language.

REAL is a synonym for SMALLFLOAT.

FLOAT [(n)] is a binary floating-point number corresponding to the‘‘double’’ data type in the C language. You can use n tospecify the precision of a FLOAT data type, although theprecision is ignored by INFORMIX-4GL. n must be a wholenumber between 1 and 14.

DOUBLEPRECISION

is a synonym for FLOAT.

MONEY [(m[,n])] is a DECIMAL type number, displayed with leading $.MONEY (m) = DECIMAL(m,2) and MONEY = DECI-MAL(16,2). See the section “Database Data Types”’ inChapter 3 for more information.

7-50 INFORMIX-4GL Statement Syntax

Page 417: Manual Informix

CREATE TABLE ( O )

SERIAL [(n)] is a sequential integer assigned automatically by 4GL. Youcan assign an initial value n. The default starting integeris 1.

DATE is a date entered as a character string in one of the formatsdescribed in the following notes.

DATETIME is a moment in time that can include the year, month, day,hour, minute, second, and fraction of a second. See the fol-lowing notes and the section “Database Data Types” inChapter 3 for more information.

INTERVAL is a positive or negative span of time that can includeyears and months, or else days, hours, minutes, seconds,and fractions of a second. See the following notes and thesection “Database Data Types”’ in Chapter 3 for moreinformation. See also Appendix J, “Working withDATETIME and INTERVAL Data.”

Notes1. 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 whenyou 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 ina statement. See the section “Owner Naming” in Chapter 3 of thismanual.

2. Table names must be unique within a database. If the database is MODEANSI, the combination owner.tablename must be unique.

3. Column names must be unique within each table, but you can use dupli-cate 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 ofthe program.

5. Users with CONNECT privilege can create temporary tables.

6. The default value in a column is NULL unless you include the NOT NULLkeywords after the data type of the column.

7. If you designate a column as NOT NULL, users must enter a value into thiscolumn when performing an INSERT or UPDATE to the table.

INFORMIX-4GL Statement Syntax 7-51

Page 418: Manual Informix

CREATE TABLE ( O )

8. 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 revokeall privileges and grant those you want. In a database created as MODEANSI, no default table-level privileges exist. You must explicitly grantthese 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. Repre-sent 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-4GLassumes 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 sinceDecember 31, 1899. You can sort DATE columns and make chronologicalcomparisons between two DATE columns.

12. The following table shows the file space requirements (in bytes) for eachdata type:

SERIAL 4SMALLINT 2INTEGER 4SMALLFLOAT 4FLOAT 8CHAR(n) nDECIMAL(m,n) 1 + m/2MONEY(m,n) 1 + m/2DATE 4DATETIME Depends on precision (see below)INTERVAL Depends on precision (see below)

Values in a DATETIME column are stored as decimal numbers, containinga sequence of digits representing the following fields: year, month, day,hour, minute, second, and fraction(n). All fields of a DATETIME columnoccupy two digits, except for the year and fraction fields. The year fieldrequires four digits. The fraction field requires n digits, rounded up to aneven number. The number of bytes required for a DATETIME column isequal to half the total number of digits for all fields, plus 1.

Values in an INTERVAL column are stored as decimal numbers, contain-ing a sequence of digits representing the following fields: year andmonth, or else year, month, day, hour, minute, second, and fraction(n). All

7-52 INFORMIX-4GL Statement Syntax

Page 419: Manual Informix

CREATE TABLE ( O )

fields of an INTERVAL column are represented by two digits, except forthe first field and the fraction field. The number of digits in the first fieldis two, unless otherwise specified as part of the qualifier. The fraction fieldrequires n digits. The number of bytes required for an INTERVAL columnis equal to half the total number of digits for all fields, rounded up to aneven 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 ofcolumns accept only unique data. A column or composite column listspecified 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 notappear 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 cannotcreate an ascending composite index on an identical composite columnlist declared as UNIQUE.

18. You can include a UNIQUE column in a composite index created with theCREATE INDEX statement.

19. Use the ALTER TABLE statement to add or drop a UNIQUE CONSTRAINTfrom a column or composite column list. You can query the syscon-straints system catalog for the names of constraints.

20. You can include up to eight columns in a unique-col-list. The total lengthof 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 usingthe template u<tabid>_<index number>. If this name conflicts with anexisting identifier, INFORMIX-4GL returns an error, and you must supplyconstr-name.

22. INFORMIX-4GL implements the UNIQUE CONSTRAINT by creating aunique index for every column declared as UNIQUE in the CREATE TABLEstatement. A row is added to the sysindexes file for each index. Eachindex 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 fromthe table-name, always use the table-name (rather than the filename) to referto the table in subsequent SQL statements.

INFORMIX-4GL Statement Syntax 7-53

Page 420: Manual Informix

CREATE TABLE ( O )

25. The pathname in an IN clause can specify any valid directory and is notrestricted to the directory that contains the current database. Use this fea-ture 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 andthe 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 log-ging. A temporary table is, therefore, always logged or never logged.

ExamplesThe 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 SERIAL(1001),order_date DATE,customer_num INTEGER,ship_instruct CHAR(40),backlog CHAR(1),po_num CHAR(10),ship_date DATE,ship_weight DECIMAL(8,2),ship_charge MONEY(6),paid_date DATE)

CREATE TABLE items(item_num SMALLINT,order_num INTEGER,

7-54 INFORMIX-4GL Statement Syntax

Page 421: Manual Informix

CREATE TABLE ( O )

stock_num SMALLINT,manu_code CHAR(3),quantity SMALLINT,total_price MONEY(8))

CREATE TABLE stock(stock_num SMALLINT,manu_code CHAR(3),description CHAR(15),unit_price MONEY(6),unit CHAR(4),unit_descr CHAR(15))

CREATE TABLE manufact(manu_code CHAR(3),manu_name CHAR(15))

CREATE TABLE state(code CHAR(2),sname CHAR(15))

The following statement creates the tab1 table. In tab1, column c1 is UNIQUEand the constraint is named uc1. A UNIQUE CONSTRAINT is also applied tothe 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

Page 422: Manual Informix

CREATE TABLE ( O )

The following statement creates the employee table. The data for the table isstored in the file /a/work/employ.dat. The index information is stored in thefile /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 datatypes:

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 adatabase that uses logging:

CREATE TEMP TABLE tab2 (fname CHAR(15), lname CHAR(15)) WITH NO LOG

Related StatementsALTER TABLE, CREATE DATABASE, CREATE INDEX, DROP DATABASE,DROP TABLE, GRANT, REVOKE

7-56 INFORMIX-4GL Statement Syntax

Page 423: Manual Informix

CREATE VIEW

CREATE VIEW

OverviewUse CREATE VIEW to create a new view based on existing tables and viewsin the database.

SyntaxCREATE VIEW view-name [ ( column-list ) ]

AS SELECT-statement [ WITH CHECK OPTION ]

ExplanationCREATE VIEW are required keywords.

view-name is an SQL identifier.

column-list is a list of one or more identifiers that name the columnsof view-name.

AS is a required keyword.

SELECT-statement is a SELECT statement.

WITH CHECKOPTION

are optional keywords.

Notes1. 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 whenyou 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 astatement, however. See the section “Owner Naming” in Chapter 3 of thismanual.

2. Except for the statements in the following list, you can use a view in anySQL statement (including form specifications) where you can use a table.

ALTER TABLE DROP INDEXALTER INDEX LOCK TABLECREATE INDEX RENAME TABLE

The view behaves like a table with the name view-name and consists of theset of rows and columns returned by the SELECT-statement each time the

INFORMIX-4GL Statement Syntax 7-57

Page 424: Manual Informix

CREATE VIEW

SQL statement is executed using the view. The view reflects changes to theunderlying tables, but with one exception.

If the view is defined with a SELECT * clause, it has only the columns thatare in the underlying tables at the time the view is created. New columnsadded subsequently to the underlying tables using the ALTER TABLEstatement will not appear in the view. See the section “Views” inChapter 3 for more information.

3. When you do not specify column-list for view-name, the view inherits thecolumn names of the underlying tables. If the SELECT-statement returns anexpression, the corresponding column in the view is called a virtual col-umn. You must provide a name for virtual columns. You must alsoprovide a column name when the select-list has duplicate column nameswhen the table prefixes are stripped. For example, when bothorders.order_num and items.order_num appear in the select-list, youmust provide two separate column names to label them in the CREATEVIEW statement.

4. Data types of the columns of the view are inherited from the tables fromwhich they come. Data types of virtual columns are determined from thenature of the expression.

5. For a database created as MODE ANSI, owner.view-name must be uniqueamong all the tables, views, and synonyms in the database. In a non-MODE ANSI database, view-name must be unique.

6. You can define a view in terms of other views, except that you must abideby the restrictions on queries listed in the section “Querying ThroughViews” in Chapter 3.

7. The SELECT-statement cannot have an ORDER BY clause nor a UNIONoperator.

8. You must have SELECT privilege on all columns from which the view isderived.

9. The WITH CHECK OPTION clause instructs INFORMIX-4GL to ensure thatall modifications to the underlying tables made through the view satisfythe definition of the view.

10. The CREATE VIEW statement cannot be rolled back.

ExampleCREATE VIEW palo_alto AS

SELECT * FROM customerWHERE city = "Palo Alto"

7-58 INFORMIX-4GL Statement Syntax

Page 425: Manual Informix

CREATE VIEW

Related StatementsCREATE TABLE, DROP VIEW

INFORMIX-4GL Statement Syntax 7-59

Page 426: Manual Informix

CURRENT WINDOW

CURRENT WINDOW

OverviewUse the CURRENT WINDOW statement to make a window the current or top-most window.

SyntaxCURRENT WINDOW IS { window-name | SCREEN }

ExplanationCURRENTWINDOW IS

are required keywords.

window-name is the name of the window that you want to be the currentwindow.

SCREEN is a keyword that refers to the entire screen.

Notes1. A window becomes completely visible when it becomes the current win-

dow. 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 cur-rent 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 thecurrent 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 inthe current window. When you change the current window while one ofthese statements is active and then resume the statement, the originalwindow is restored as the current window. For example, you can use anON KEY clause in an INPUT statement to allow the user to open a new win-

7-60 INFORMIX-4GL Statement Syntax

Page 427: Manual Informix

CURRENT WINDOW

dow by pressing a specific key during input. When the user presses thedesignated key, INFORMIX-4GL executes the statements in the ON KEYclause and then resumes input from the window that was current beforethe 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 listor ‘‘stack’’ of all open windows. It adds the current window to its windowlist whenever you open a new window. The new window then becomesthe current window. When you close a window, INFORMIX-4GL removesit 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 windowlist by moving the new current window to the top, and closing the gap inthe list left by this window.

ExamplesCURRENT WINDOW IS win1

CURRENT WINDOW IS SCREEN

Related StatementsCLEAR WINDOW, CLOSE WINDOW, OPEN WINDOW, OPTIONS

INFORMIX-4GL Statement Syntax 7-61

Page 428: Manual Informix

DATABASE

DATABASE

OverviewUse the DATABASE statement to declare an accessible database as the currentdatabase.

SyntaxDATABASE database-name [ EXCLUSIVE ]

ExplanationDATABASE is a required keyword.

database-name is the name of a database, or a program variable that evalu-ates to the name of a database.

EXCLUSIVE is an optional keyword.

Notes1. 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 keywordwith a program variable that evaluates to the full pathname of the data-base (excluding the .dbs extension).

2. In an INFORMIX-4GL program, the DATABASE statement can serve twopurposes, one procedural and the other non-procedural. It makes thenamed database the current database (procedural), and it tells the com-piler where to find information about variables defined LIKE columns ina table (non-procedural).

To serve the non-procedural purpose, the DATABASE statement mustoccur outside any routine and precede the GLOBALS statements whenyou use indirect data typing with the LIKE clause. The database-name mustbe explicitly expressed and not given as a program variable. You cannotuse the EXCLUSIVE keyword in this context. If you use the DATABASEstatement in this non-procedural way, INFORMIX-4GL begins the MAINprogram block with the database-name as the current database.

Ordinarily, you use only one database, and the preceding procedure isenough. If you do not have global variables defined LIKE database col-umns, but still want to interact with a database, you can use the

7-62 INFORMIX-4GL Statement Syntax

Page 429: Manual Informix

DATABASE

DATABASE statement in a purely procedural way. In this case, it mustoccur within a routine and must follow any DEFINE statements withinthat routine. In this case, database-name can be a program variable, andyou 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 cannotdefine variables LIKE columns in the second database.

5. The EXCLUSIVE option opens the database in an exclusive mode andallows only the current user access to the database. To allow others accessto the database, you must execute the CLOSE DATABASE statement andthen reopen the database.

6. You can determine the type of database a user selects by checking thewarning flag after a DATABASE statement in the SQLCA.SQLAWARNstructure. See the section “SQLCA Record” in Chapter 3 for more infor-mation about SQLCA.SQLAWARN.

7. You cannot include the DATABASE statement in a multi-statementPREPARE.

ExampleDATABASE stores

Related StatementsCREATE DATABASE, DROP DATABASE, CLOSE DATABASE

INFORMIX-4GL Statement Syntax 7-63

Page 430: Manual Informix

DECLARE

DECLARE

OverviewUse the DECLARE statement to assign a cursor name to a SELECT or INSERTstatement. A cursor is required for a SELECT statement that selects more thanone row.

SyntaxDECLARE cursor-name [ SCROLL ] CURSOR [ WITH HOLD ] FOR

{ SELECT-statement [ FOR UPDATE [ OF column-list ] ] |INSERT-statement | statement-id }

ExplanationDECLARE is a required keyword.

cursor-name is an INFORMIX-4GL identifier.

SCROLL is an optional keyword that can be used only with a state-ment or a statement_id of a SELECT statement that youPREPAREd.

CURSOR FOR are required keywords.

WITH HOLD are optional keywords to prevent the cursor from beingclosed when each transaction ends.

SELECT-statement is a SELECT statement.

FOR UPDATE are keywords that are required if the cursor will be usedto modify existing rows.

OF is an optional keyword.

column-list is a list of column names from tables listed in the FROMclause of SELECT-statement.

INSERT-statement is an INSERT statement.

statement-id is the identifier of an INSERT or SELECT statement thatyou previously PREPAREd.

Notes1. 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

Page 431: Manual Informix

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 Informixextensions to ANSI standard syntax. You receive a warning if you compilewith the -ansi flag, or if you have set the DBANSIWARN environment vari-able and include the SCROLL, INSERT, or WITH HOLD keywords in aprogram.

4. Unless you include the WITH HOLD keywords, INFORMIX-4GL closes thecursor after each transaction. (A CLOSE DATABASE statement closes allcursors, including cursors WITH HOLD.)

5. The following rules apply when you use cursor manipulation statementsin a non-MODE ANSI database with explicit transactions:

• You must OPEN and CLOSE a regular cursor that is FOR UPDATE andan 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 atransaction.

• You can OPEN and CLOSE a cursor WITH HOLD that is FOR UPDATEoutside a transaction. Any FETCH using it, however, must take placewithin a transaction.

These requirements are automatically satisfied if the current database is aMODE ANSI database.

6. Unlike other cursors, a cursor WITH HOLD is not closed when you executea COMMIT WORK or ROLLBACK WORK statement. You must explicitlyCLOSE a cursor WITH HOLD. (A CLOSE DATABASE statement closes allcursors, including cursors WITH HOLD.)

7. You must include the SCROLL keyword in the DECLARE statement for aSELECT cursor if you are going to issue a statement that includes thePREVIOUS, 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 state-ment in a previous PREPARE statement.

9. The column names in an OF column-list clause do not need to be in theselect-list of the SELECT clause.

10. If the SELECT statement has no INTO clause, the subsequent FETCH state-ment must specify INTO variable-list.

INFORMIX-4GL Statement Syntax 7-65

Page 432: Manual Informix

DECLARE

11. Do not use INTO with an array element subscripted by a variable in theSELECT statement because the subscript is evaluated at the time of theDECLARE, not at the time of any subsequent FETCH. You can use a con-stant to indicate the array element.

Use FETCH INTO when the output variable is an array element sub-scripted by a variable or a constant.

12. You cannot use the FOR UPDATE clause in the DECLARE statement for aSELECT 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 asingle table.

14. You must use the FOR UPDATE clause in the DECLARE statement for anon-scrolling SELECT cursor if you will later use either the UPDATE or theDELETE statement with the WHERE CURRENT OF cursor-name option. Thecursor FOR UPDATE can include or omit WITH HOLD.

15. If you specify one or more columns in the FOR UPDATE clause, you canupdate only those columns in a subsequent UPDATE WHERE CURRENTOF statement. (If you do not specify any columns in the FOR UPDATEclause, you can update any column in a subsequent UPDATE WHERECURRENT OF statement.)

16. When you DECLARE a cursor FOR UPDATE, each FETCH executed on thatcursor locks the FETCHed row in exclusive mode. For a database withouttransactions, the lock is released when you execute the next FETCH state-ment or when you CLOSE the cursor (whichever occurs first), regardlessof whether you UPDATE the row.

For a database with transactions, each row that you UPDATE remainslocked for the duration of the transaction. These locks are released onlywhen you end the transaction (issue a COMMIT WORK or ROLLBACKWORK statement).

See the section“Locking” in Chapter 3 for a more detailed description oftable-level and row-level locking.

17. If your database has a transaction log but is not MODE ANSI, you mustissue a BEGIN WORK statement before you OPEN a cursor that youDECLAREd FOR UPDATE but not WITH HOLD. (You can DECLARE a cur-sor WITH HOLD FOR UPDATE outside a transaction, but you cannot rollback any changes to a non-MODE ANSI database that the cursor performsoutside a transaction. In this situation, each UPDATE is automaticallycommitted as a singleton transaction.)

7-66 INFORMIX-4GL Statement Syntax

Page 433: Manual Informix

DECLARE

18. INFORMIX-4GL evaluates the variables in a DECLARE statement at thetime when you OPEN the cursor, except for those variables that includesubscripts. INFORMIX-4GL evaluates the subscript when you DECLAREthe cursor and evaluates the variable when you OPEN the cursor.

In the following example, INFORMIX-4GL selects rows where the value inthe customer_num column equals 106 :

LET a = 101DECLARE q_curs CURSOR FOR

SELECT * FROM orders WHERE customer_num = aLET a = 106OPEN q_curs

In the next example, INFORMIX-4GL selects rows where the value in thecustomer_num column equals a[5] :

LET i = 5DECLARE q_curs CURSOR FOR

SELECT * FROM orders WHERE customer_num = a[i]LET i = 2OPEN q_curs

19. You cannot DECLARE a cursor for an INSERT statement that contains anembedded SELECT statement.

20. If you DECLARE a cursor for an INSERT statement that has a VALUESclause containing only constants, INFORMIX-4GL does not create a buffer,but merely keeps count of the number of inserts. Such inserts are neverflushed as the result of a PUT statement. Flushing occurs when you issuea FLUSH or CLOSE cursor statement.

21. The DECLARE statement for a cursor must physically appear before anystatement that specifies the cursor. The cursor-name has meaning from thepoint at which you DECLARE it, to the end of the same source file. It is nota 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

Page 434: Manual Informix

DECLARE

ExamplesDECLARE scurs CURSOR FOR

SELECT * FROM customer

DECLARE wh_curs CURSOR WITH HOLD FOR st_1

DECLARE ucurs CURSOR FORSELECT * FROM customer WHERE customer_num > 110FOR UPDATE OF fname, lname

DECLARE icurs CURSOR FORINSERT INTO stock

VALUES (stock_no, man_code, descr, u_price,unit, u_desc)

DECLARE s_curs SCROLL CURSOR FORSELECT * FROM ordersWHERE customer_num = 104

Related StatementsCLOSE, DELETE, FETCH, FLUSH, FOREACH, FREE, OPEN, PREPARE, PUT,SELECT, UPDATE

7-68 INFORMIX-4GL Statement Syntax

Page 435: Manual Informix

DEFER

DEFER

OverviewUse the DEFER statement to keep INFORMIX-4GL from terminating your pro-gram whenever a user presses the Interrupt key (usually CTRL-C or DEL) orthe QUIT key (usually CTRL-\).

SyntaxDEFER { INTERRUPT | QUIT }

ExplanationDEFER is a required keyword.

INTERRUPT is an optional keyword.

QUIT is an optional keyword.

Notes1. In the absence of the DEFER statement, your program will stop immedi-

ately whenever Interrupt or Quit is pressed.

2. The DEFER statement sets a global flag (int_flag for INTERRUPT andquit_flag for QUIT) to non-zero whenever the user presses the Interruptor Quit key. The programmer must reset the flags to zero.

3. If the DEFER INTERRUPT statement has been executed and the user subse-quently enters an Interrupt during an INPUT statement, program controlwill leave the INPUT statement and int_flag will be set. This applies to theCONSTRUCT, INPUT ARRAY, and PROMPT statements, as well.

4. The DEFER INTERRUPT statement can occur only once in a program, andthen only in the MAIN program block. After being executed, it remains ineffect for the duration of the program. This characteristic applies as wellto the DEFER QUIT statement.

ExampleDEFER INTERRUPT

INFORMIX-4GL Statement Syntax 7-69

Page 436: Manual Informix

DEFER

Related StatementWHENEVER

7-70 INFORMIX-4GL Statement Syntax

Page 437: Manual Informix

DEFINE

DEFINE

OverviewUse the DEFINE statement to define identifiers in your program and to setaside adequate memory for each 4GL program variable.

SyntaxDEFINE variable-list { type

| LIKE table.column| RECORD { LIKE table.* | variable-list [ , . . . ]

END RECORD } } [ , . . . ]

ExplanationDEFINE is a required keyword.

variable-list is one or more identifiers of program variable.

type is one of these data types (as defined in Chapter 2):

SMALLINT MONEY [ (m [ , n ] ) ]

INTEGER CHAR [ ( n ) ]INT CHARACTER [ ( n ) ]

DECIMAL [ (m [ , n ] ) ] DATEDEC [ ( m [ , n ] ) ]NUMERIC [ (m [ , n ] ) ] DATETIME qualifier

SMALLFLOAT INTERVAL qualifierREALRECORD [ LIKE table. * ]FLOAT [ ( n ) ]DOUBLE PRECISION [ ( n ) ] ARRAY [ i , j , k ] OF type

LIKE is a keyword to specify the data type indirectly.

table.column is the full identifier for a column in the current database. TheDATABASE statement must precede DEFINE statements thatuse indirect typing.

RECORD is a data type that describes a set of variables of possiblydiffering database data types.

table is the name of a database table.

ENDRECORD

are keywords that follow the declaration of the last element ofa program record.

INFORMIX-4GL Statement Syntax 7-71

Page 438: Manual Informix

DEFINE

Notes1. Elements of records are addressed as record_name. column_name.

2. If the DEFINE statement is used in a function or MAIN program block, itmust be the first statement to appear in that function or MAIN programblock.

3. See the “Data Types” section in Chapter 2 for a full discussion of 4GL datatypes for 4GL variables.

4. The section “Language Conventions” in Chapter 2 describes the identifi-ers of 4GL variables and their scope of reference.

ExampleDEFINE p_customer RECORD LIKE customer.*,

p_orders RECORDorder_num LIKE orders.order_num,order_date LIKE orders.order_date,po_num LIKE orders.po_num,ship_instruct LIKE orders.ship_instructEND RECORD,

p_stock ARRAY[30] OF RECORDs_num LIKE stock.stock_num,m_code LIKE stock.manu_codeEND RECORD,

stock_tot SMALLINT

Related StatementsGLOBALS, LET

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

7-72 INFORMIX-4GL Statement Syntax

Page 439: Manual Informix

DELETE

DELETE

OverviewUse the DELETE statement to delete one or more rows from a table.

SyntaxDELETE FROM table-name

[ WHERE { condition | CURRENT OF cursor-name } ]

ExplanationDELETE FROM are required keywords.

table-name is the name of the table from which you want to delete rows.

WHERE is a keyword.

condition is a condition of a standard WHERE clause. (See the SELECTstatement for further information.) INFORMIX-4GL deletesall rows that satisfy the condition in the WHERE clause.

CURRENT OF are keywords.

cursor-name is the SQL identifier of a previously DECLAREd and posi-tioned cursor.

Notes1. When you create a database with transactions that is not MODE ANSI,

each DELETE statement you execute is treated as a single transaction, evenif you do not use the BEGIN WORK and COMMIT WORK or ROLLBACKWORK statements.

2. Each row affected by a DELETE statement within a transaction is lockedfor the duration of the transaction; therefore, a single DELETE statementthat affects a large number of rows locks the rows until the entire opera-tion is completed. If the number of rows affected is very large, you mightexceed the limits that your operating system places on the maximumnumber of simultaneous locks. If you exceed these limits, you may wantto either reduce the scope of the DELETE statement or lock the entire tablebefore executing the statement.

See the section “Locking” in Chapter 3 for a more detailed description oftable-level and row-level locking in INFORMIX-4GL.

INFORMIX-4GL Statement Syntax 7-73

Page 440: Manual Informix

DELETE

3. To use the WHERE CURRENT OF option, you must have previouslyDECLAREd the cursor-name with the FOR UPDATE option.

4. If you use the CURRENT OF option, DELETE removes the row of the activeset at the current position of the cursor. The cursor is left pointingbetween the remaining rows and you cannot use it for DELETE or UPDATEuntil you reposition it with a FETCH statement.

5. If your database has transactions and you use the WHERE CURRENT OFclause, you must execute the DELETE statement within a transaction.

ExamplesDELETE FROM items

WHERE order_num = onum

DELETE FROM ordersWHERE CURRENT OF query_cursor

These statements remove all items belonging to the order number set in theprogram variable onum from the items table and remove the row from theorders table pointed to by the cursor query_cursor.

Related StatementsDECLARE, INSERT, UPDATE

7-74 INFORMIX-4GL Statement Syntax

Page 441: Manual Informix

DISPLAY

DISPLAY

OverviewUse the DISPLAY statement to display data values on the screen.

SyntaxDISPLAY{ BY NAME variable-list |

variable-list [ TO { field-list | screen-record [ [ n ] ].* } [ , . . . ]| AT row, column ] }

[ ATTRIBUTE ( attribute-list ) ]

ExplanationDISPLAY is a required keyword.

BY NAME are keywords instructing INFORMIX-4GL to match thenames of variables with screen field names.

variable-list is a required list of one or more program variables and/orconstants, separated by commas.

TO is a keyword to specify that INFORMIX-4GL will display thevariable_list in screen fields or in a screen array.

field-list is a list of one or more screen field names in the currentscreen form.

screen-record is the identifier of a collection of field names defined in aform specification as a SCREEN RECORD.

[ n ] is an integer, enclosed in brackets, to specify the row of ascreen array (beginning with line 1) where the variable-listshould be displayed.

AT is a keyword to specify coordinates of a location on thescreen or in the current window.

row is an integer variable or constant, indicating a row of thescreen or current window.

column is an integer variable or constant, indicating a column of thescreen or current window.

ATTRIBUTE is a keyword to specify screen display attributes.

(attribute-list) is a list (in parentheses) of one or more screen displayattributes, separated by commas.

INFORMIX-4GL Statement Syntax 7-75

Page 442: Manual Informix

DISPLAY

Notes1. The DISPLAY statement (without the BY NAME, TO, or AT keywords)

displays variable-list on the next line. This can format displayed valueswith 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 cur-rent screen display until this statement is executed again.

3. INFORMIX-4GL displays number values right justified, and characterstrings left justified in the screen field.

4. If a character value does not fit in the field, its display is truncated. If anumber value does not fit in the field, INFORMIX-4GL fills the field withasterisks (*) to indicate an overflow.

5. The DISPLAY BY NAME option selects screen fields, based on the identityof the program variable name and the field name. INFORMIX-4GL usesonly the suffix portion of these variable names and field names. Thisoption results in an error (setting status < 0) unless the suffixes are uniqueand unambiguous.

6. The DISPLAY TO screen-record [n].* option lists constants or program vari-ables on the nth row of a screen array. You can move such values up ordown with the SCROLL statement.

7. You can use the DISPLAY AT statement to display variable-list at a specifiedlocation on the screen or in the current window. You can use CLIPPED andUSING to format displayed values.

8. The coordinates start with row 1 and column 1 in the upper left cornerof the screen or current 4GL window. The row coordinates increase as yougo down, and the column coordinates increase as you move from left toright. On a standard terminal screen, the lower right corner has thecoordinates (24, 80).

9. An error occurs (setting status < 0 ) if either the row or column exceeds thedimensions of the screen or of the current window.

10. If you use the AT option when the last element of variable-list is a NULLCHAR 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 ATstatement, INFORMIX-4GL clears the screen or the current window beforeproducing the second display.

7-76 INFORMIX-4GL Statement Syntax

Page 443: Manual Informix

DISPLAY

12. If no TO clause or AT clause specifies a location, a compile-time erroroccurs if you use the ATTRIBUTE clause.

13. In a DISPLAY TO statement, any screen attributes specified in attribute-listapply to all the fields in field-list or screen-record.

14. If you use the ATTRIBUTE clause, none of the default attributes listedin syscolatt or in the form specification file for fields in field-list orscreen-record apply. The attribute-list temporarily overrides any attributesspecified in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statementfor these fields.

15. These keywords can appear in the ATTRIBUTE clause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

You can specify zero or one of the keywords in the left-hand columns, andfrom zero to three from the right-hand column (but some terminals maynot support some combinations). On color terminals, NORMAL is inter-preted 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 onmonochrome terminals of keywords that specify color.

These keywords cannot produce the effects suggested by their namesunless the termcap or terminfo files and the physical terminals supportthe attribute. (See Appendix I, “Modifying termcap and terminfo.”)

Note: Some terminal entries in termcap or terminfo include the sg#1 orxmc#1 capabilities. On these terminals, the first character of variable-list isreplaced by a blank if you use the DISPLAY AT statement with any displayattribute. To be safe, make sure that the first character of the variable-list is ablank if you specify any display attributes.

16. On UNIX systems that use terminfo files rather than termcap, INFOR-MIX-4GL does not support attributes that specify colors, and the onlyvalid attribute-list keywords are REVERSE and UNDERLINE.

INFORMIX-4GL Statement Syntax 7-77

Page 444: Manual Informix

DISPLAY

ExamplesDISPLAY BY NAME lname, fname

DISPLAY "There are ", num USING "- #### "," items in the list" AT 12,1ATTRIBUTE(REVERSE, BLUE)

DISPLAY add_cust.* TO sc_addr[4].*

Related StatementsINPUT, DISPLAY ARRAY, DISPLAY FORM, OPEN WINDOW

7-78 INFORMIX-4GL Statement Syntax

Page 445: Manual Informix

DISPLAY ARRAY

DISPLAY ARRAY

OverviewUse the DISPLAY ARRAY statement to display a program array in a screenarray, and to permit scrolling through the array.

SyntaxDISPLAY ARRAY record-array TO screen-array.*

[ ATTRIBUTE ( attribute-list ) ]{ ON KEY ( key-list )

statement. . .

[ EXIT DISPLAY ]. . .

END DISPLAY | [ END DISPLAY ] }

ExplanationDISPLAY ARRAY are required keywords.

record-array is a program array name. Usually, record-array is an arrayof records.

TO is a required keyword.

screen-array is the name of a screen record, defined in a form specifica-tion file, that corresponds to the fields in a row of a screenarray.

ATTRIBUTE is an optional keyword.

attribute-list is a list of one or more screen-display attributes.

ON KEY are optional keywords.

key-list is usually a list of one or more function or CTRL key des-ignations. It can also include ESC (if you have specifiedanother key as the Accept key in the OPTIONS statement)or INTERRUPT (if you have executed a DEFER INTERRUPTstatement).

statement is an INFORMIX-4GL statement.

EXIT DISPLAY is a statement that causes INFORMIX-4GL to exit from theDISPLAY ARRAY statement.

END DISPLAY is a statement that terminates a DISPLAY ARRAY state-ment. It is required only when an ON KEY clause is used,

INFORMIX-4GL Statement Syntax 7-79

Page 446: Manual Informix

DISPLAY ARRAY

or when the DISPLAY ARRAY statement appears as thelast statement in a clause and is followed by an ON KEYclause.

Notes1. 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 timeand to scroll to the bottom of the screen array; the [ ↑ ] key to move thecursor 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. Youcan use the OPTIONS statement to assign these functions to other keys. Inaddition, you must define the key assignments properly in the termcap orterminfo files.

3. The user can exit from the DISPLAY ARRAY statement by pressing ESC, orby pressing the key specified as the ACCEPT KEY in the OPTIONS state-ment. The program should tell the user to do this.

4. The following conditions require that an END DISPLAY statement appearin your program:

• The DISPLAY ARRAY statement includes one or more ON KEY clauses.

• The DISPLAY ARRAY statement appears as the last statement in aclause (within an INPUT statement, for example) and is followed by anON KEY clause.

5. By default, INFORMIX-4GL displays number variables right-justified andcharacter variables left-justified in the screen field.

6. If a displayed character value is larger than the field, INFORMIX-4GLtruncates 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 insyscolatt or in the form specification file for the fields in screen-array willapply.

7-80 INFORMIX-4GL Statement Syntax

Page 447: Manual Informix

DISPLAY ARRAY

9. The following list shows the screen attributes allowed in the ATTRIBUTEclause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

On color terminals, NORMAL is interpreted as WHITE; BOLD as RED; DIMas BLUE; and INVISIBLE as BLACK. If you have a colornames file, you canuse the color names listed there.

10. INFORMIX-4GL passes control to the statements following an ON KEYclause when the user presses a key in key-list. After executing the state-ments in the ON KEY clause, INFORMIX-4GL resumes the display with thecursor in the same location as before the ON KEY break, unless NEXTFIELD and EXIT DISPLAY are implemented.

11. The notation for function keys is F1, F2, F3, . . . F36 . The nota-tion 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 Inter-rupt key is INTERRUPT.

12. By default, both ESCAPE and INTERRUPT are exits from the DISPLAYARRAY statement. If the DEFER INTERRUPT statement has been executed,an INTERRUPT causes INFORMIX-4GL to set int_flag to non-zero, and ter-minates the DISPLAY ARRAY statement (unless the Interrupt key has beenredefined in an ON KEY clause). Otherwise, an Interrupt causes an imme-diate program stop.

13. You can include the following keys in a key-list under the statedconditions:

• ESCAPE, if you have specified another key as the Accept key in theOPTIONS statement.

• [ F3 ], if you have specified another key as the Next key in the OPTIONSstatement.

• [ F4 ], if you have specified another key as the Previous key in theOPTIONS statement.

• The Interrupt key, if you have executed a DEFER INTERRUPT state-ment. (When the user presses the Interrupt key under theseconditions, INFORMIX-4GL executes the statements in the ON KEY

INFORMIX-4GL Statement Syntax 7-81

Page 448: Manual Informix

DISPLAY ARRAY

clause and sets int_flag to non-zero but does not terminate theDISPLAY 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 CTRLkeys are reserved for editing functions in the CONSTRUCT, INPUT, andINPUT ARRAY statements.

• Other keys that have special meaning for your operating system.

14. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within theON KEY clause of a DISPLAY ARRAY statement. You can, however, call afunction that executes one of these statements.

ExamplesDISPLAY 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 StatementsDISPLAY, SCROLL

7-82 INFORMIX-4GL Statement Syntax

Page 449: Manual Informix

DISPLAY FORM

DISPLAY FORM

OverviewUse the DISPLAY FORM statement to display a pre-compiled screen form.

SyntaxDISPLAY FORM form-name [ ATTRIBUTE ( attribute-list ) ]

ExplanationDISPLAY FORM are required keywords.

form-name is an INFORMIX-4GL identifier that has been associated witha screen form in an OPEN FORM statement.

ATTRIBUTE is an optional keyword.

attribute-list is a list of one or more screen attributes that will apply to thedelimiters of the screen form, and to any text outside displayfields.

Notes1. 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 win-dows (including the screen) by using the OPTIONS statement or for aspecific window by using an ATTRIBUTE clause in the appropriate OPENWINDOW statement.

2. The following list shows the screen attributes allowed in the ATTRIBUTEclause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIMas BLUE, and INVISIBLE as BLACK. If you have a colornames file, you canuse the color names listed there. (See Appendix I.)

INFORMIX-4GL Statement Syntax 7-83

Page 450: Manual Informix

DISPLAY FORM

3. INFORMIX-4GL issues an error if a window is not large enough to displaya form. See Chapter 13 of the INFORMIX-4GL User Guide and the OPENWINDOW statement in this chapter for more information about display-ing a form in a window.

4. The DISPLAY FORM statement is not required if you opened and dis-played a form using the WITH FORM option of the OPEN WINDOWstatement.

ExamplesDISPLAY FORM order_entry

DISPLAY FORM inventory ATTRIBUTE(BLUE)

Related StatementsCLEAR, CLOSE FORM, OPEN FORM, OPEN WINDOW

7-84 INFORMIX-4GL Statement Syntax

Page 451: Manual Informix

DROP AUDIT

DROP AUDIT

OverviewUse the DROP AUDIT statement to delete an audit trail file.

SyntaxDROP AUDIT FOR table-name

ExplanationDROP AUDIT FOR are required keywords.

table-name is the name of the table whose audit trail file you wantto delete.

Notes1. 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 AUDITstatement to start a new audit trail and then back up the table. See the sec-tion “Audit Trails” in Chapter 3 for more information.

2. You must own table-name or have DBA status to use the DROP AUDITstatement.

ExampleDROP AUDIT FOR orders

Related StatementsCREATE AUDIT, RECOVER TABLE

INFORMIX-4GL Statement Syntax 7-85

Page 452: Manual Informix

DROP DATABASE

DROP DATABASE

OverviewUse the DROP DATABASE statement to delete an entire database, including allsystem catalogs, indexes, data, and the transaction log.

SyntaxDROP DATABASE { database-name | char-variable }

ExplanationDROP DATABASE are required keywords.

database-name is the name of the database you want to delete.

char-variable is a program variable of type CHAR containing thename of the database you want to delete.

Notes1. 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 ifthere are any files in the database directory other than those created fordatabase tables and their indexes.

3. You cannot drop the current database. You must execute the CLOSEDATABASE statement first.

4. The DROP DATABASE statement cannot be rolled back.

5. For databases with transactions, the DROP DATABASE statement deletesthe transaction log.

6. The DROP DATABASE statement cannot appear in a multi-statementPREPARE.

ExampleDROP DATABASE stores

7-86 INFORMIX-4GL Statement Syntax

Page 453: Manual Informix

DROP DATABASE

Related StatementsCREATE DATABASE, CLOSE DATABASE

INFORMIX-4GL Statement Syntax 7-87

Page 454: Manual Informix

DROP INDEX

DROP INDEX

OverviewUse the DROP INDEX statement to delete an index.

SyntaxDROP INDEX index-name

ExplanationDROP INDEX are required keywords.

index-name is the name of the index you want to delete.

Notes1. 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 columnlist is identified as having a UNIQUE CONSTRAINT in the CREATE TABLEstatement.

ExampleDROP INDEX i_ordnum

Related StatementCREATE INDEX

7-88 INFORMIX-4GL Statement Syntax

Page 455: Manual Informix

DROP SYNONYM

DROP SYNONYM

OverviewUse the DROP SYNONYM statement to delete a previously defined synonymfor a table or view.

SyntaxDROP SYNONYM synonym

ExplanationDROP SYNONYM are required keywords.

synonym is a 4GL identifier.

Notes1. 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 isreplaced in the compiled program by the real identifier of the table orview (as listed in the systables system catalog). If you subsequently dropthe synonym, the compiled program will still run.

3. The DROP SYNONYM statement cannot be rolled back.

ExampleDROP SYNONYM cust

Related StatementCREATE SYNONYM

INFORMIX-4GL Statement Syntax 7-89

Page 456: Manual Informix

DROP TABLE

DROP TABLE

OverviewUse the DROP TABLE statement to delete a table, along with its associatedindexes and data.

SyntaxDROP TABLE table-name

ExplanationDROP TABLE are required keywords.

table-name is the name of the table you want to delete.

Notes1. 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 youhave 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 DROPTABLE statement.

4. The DROP TABLE statement cannot be rolled back.

ExampleDROP TABLE customer

Related StatementCREATE TABLE

7-90 INFORMIX-4GL Statement Syntax

Page 457: Manual Informix

DROP VIEW

DROP VIEW

OverviewUse the DROP VIEW statement to delete a view from the database.

SyntaxDROP VIEW view-name

ExplanationDROP VIEW are required keywords.

view-name is the identifier of a view.

Notes1. 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 definedin terms of view-name.

3. You cannot roll back the DROP VIEW statement.

4. See the section “Views” in Chapter 3 for more information.

ExampleDROP VIEW cust1

Related StatementsCREATE VIEW, DROP TABLE

INFORMIX-4GL Statement Syntax 7-91

Page 458: Manual Informix

ERROR

ERROR

OverviewUse the ERROR statement to display an error message on the Error line (bydefault, the bottom line of the screen), and to ring the terminal bell.

SyntaxERROR display-list [ ATTRIBUTE ( attribute-list ) ]

ExplanationERROR is a required keyword.

display-list is a list of one or more program variables and/or string con-stants (enclosed in quotation marks), separated by commas.

ATTRIBUTE is an optional keyword.

attribute-list is a list of one or more screen attributes, separated bycommas.

Notes1. 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 onthe 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 thecurrent 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 thedefault attribute with the ATTRIBUTE clause.

7-92 INFORMIX-4GL Statement Syntax

Page 459: Manual Informix

ERROR

5. The following list shows the screen attributes allowed in the ATTRIBUTEclause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIMas BLUE, and INVISIBLE as BLACK. If you have a colornames file, you canuse the color names listed there. (See Appendix I.)

ExampleERROR "There is no match for ", pattern

Related StatementsDISPLAY, MESSAGE, OPTIONS

INFORMIX-4GL Statement Syntax 7-93

Page 460: Manual Informix

EXECUTE

EXECUTE

OverviewUse the EXECUTE statement to run a statement specified by a previousPREPARE statement.

SyntaxEXECUTE statement-id [ USING input-list ]

ExplanationEXECUTE is a required keyword.

statement-id is an SQL statement identifier that you named in a previousPREPARE statement.

USING is an optional keyword.

input-list is a list of program variables to be substituted as valuesfor the question marks (?) in the statement indicated bystatement-id. Use this option when you know the numberand data types of the values that the PREPAREd statementrequires.

Notes1. 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 ofthe PREPAREd statement. The data type of each variable in input-list mustbe compatible with the value expected in the PREPAREd statement for thecorresponding parameter.

3. You cannot EXECUTE a PREPAREd SELECT statement. You must useDECLARE with a FOREACH loop, or use the OPEN, FETCH, and CLOSEstatements 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 pro-cess as a group.

7-94 INFORMIX-4GL Statement Syntax

Page 461: Manual Informix

EXECUTE

5. The scope of reference of the statement-id is from the PREPARE statementthat names it until the end of its source-code module. The EXECUTE state-ment cannot reference a statement-id that you PREPARE in a differentmodule, or later in the same module.

6. PREPAREd statements require database engine resources that are notunlimited. If you specify FREE statement-id to release engine resources,you cannot subsequently EXECUTE that statement unless you PREPARE itagain.

ExampleLET s1 = "UPDATE orders SET po_num = ?, order_date = ?"

PREPARE statement_1 FROM s1

EXECUTE statement_1 USING purchase_num, order_date

Related StatementsDECLARE, FREE, PREPARE

INFORMIX-4GL Statement Syntax 7-95

Page 462: Manual Informix

EXIT

EXIT

OverviewUse the EXIT statement to terminate the program; to break out of a FOR, aFOREACH, or a WHILE loop; to leave the CASE statement; to leave the INPUTor INPUT ARRAY statement; or to leave a menu.

SyntaxEXIT { CASE | DISPLAY | FOR | FOREACH | INPUT | MENU

| PROGRAM [ ( integer-expr ) ] | WHILE }

ExplanationEXIT is a required keyword.

CASE is an optional keyword.

DISPLAY is an optional keyword.

FOR is an optional keyword.

FOREACH is an optional keyword.

INPUT is an optional keyword.

MENU is an optional keyword.

PROGRAM is an optional keyword.

integer-expr is an expression that evaluates as an integer.

WHILE is an optional keyword.

Notes1. You can use the CASE option only within a CASE statement, the DISPLAY

option only within a DISPLAY ARRAY statement, the FOR option onlywithin a FOR statement, the FOREACH option only within a FOREACHstatement, the INPUT option only within an INPUT or INPUT ARRAYstatement, the MENU option only following a COMMAND clause of aMENU statement, and the WHILE option only within a WHILE statement.

In each case, program control passes to the first statement following theEND CASE, END DISPLAY, END FOR, END FOREACH, END INPUT, ENDMENU, or END WHILE statements, respectively.

7-96 INFORMIX-4GL Statement Syntax

Page 463: Manual Informix

EXIT

2. You can use the PROGRAM option anywhere; it immediately terminatesthe program.

3. Use the optional integer argument of EXIT PROGRAM to return a statuscode to the operating system upon program termination.

Related StatementCONTINUE

INFORMIX-4GL Statement Syntax 7-97

Page 464: Manual Informix

FETCH

FETCH

OverviewUse the FETCH statement to move the cursor to a new row in the active setand to retrieve the values from that row.

SyntaxFETCH [ NEXT | { PREVIOUS | PRIOR } | FIRST | LAST | CURRENT |

RELATIVE m | ABSOLUTE n ] cursor-name[ INTO variable-list ]

ExplanationFETCH is a required keyword.

NEXT is a keyword indicating the next row in the active list. NEXTis the default.

PREVIOUS is a keyword indicating the prior row in the active list.

PRIOR is a keyword that is synonymous with PREVIOUS.

FIRST is a keyword indicating the first row of the active list.

LAST is a keyword indicating the last row of the active list.

CURRENT is a keyword indicating the current row of the active list.

RELATIVE m is a keyword indicating the mth row relative to the currentcursor position in the active list. Here m can be either an inte-ger or a program variable and can be either positive ornegative.

ABSOLUTE n is a keyword indicating the nth row in the active list. Here ncan be either an integer or a program variable.

cursor-name is a 4GL identifier that you specified in a previous DECLAREstatement. You must also OPEN cursor-name.

INTO is an optional keyword.

variable-list is a list of 4GL program variables that contains the columnvalues of the row pointed to by cursor-name.

7-98 INFORMIX-4GL Statement Syntax

Page 465: Manual Informix

FETCH

Notes1. FETCH NEXT is the default condition.

2. You must DECLARE a SCROLL cursor before issuing a FETCH statementthat 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 thatcursor. If the SELECT statement has no INTO clause, the FETCH statementmust have one.

4. You can FETCH into a program array element only by using an INTOclause in the FETCH statement. Do not refer to an array element in theSELECT-statement of a DECLARE statement.

5. Under any of the following circumstances, INFORMIX-4GL returns a ‘‘rownot found’’ code (status = NOTFOUND ).

• You issue a FETCH NEXT statement when the cursor points to the lastrow in the active set.

• You issue a FETCH PRIOR or FETCH PREVIOUS statement when thecursor points to the first row in the active set.

• You issue a FETCH ABSOLUTE n statement when no nth row exists inthe active set.

• You issue a FETCH RELATIVE m statement when no mth row exists inthe active set.

You can use the WHENEVER NOT FOUND statement to specify an actionto take if status = NOTFOUND.

6. FETCH does not lock a row unless the DECLARE statement contains aSELECT with a FOR UPDATE clause. It is possible to retrieve a row that isbeing UPDATEd or DELETEd by a concurrent process.

7. If the cursor was DECLAREd FOR UPDATE and the current database is notMODE ANSI but uses explicit transactions, you can include FETCH onlywithin a transaction (that is, following a BEGIN WORK statement). In aMODE ANSI database, all operations take place inside a transaction, so aFETCH can be done at any time while cursor-name is OPEN.

INFORMIX-4GL Statement Syntax 7-99

Page 466: Manual Informix

FETCH

ExamplesFETCH 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 StatementsCLOSE, DECLARE, DELETE, FOREACH, OPEN, PREPARE, PUT, SELECT,UPDATE, WHENEVER

7-100 INFORMIX-4GL Statement Syntax

Page 467: Manual Informix

FINISH REPORT

FINISH REPORT

OverviewUse the FINISH REPORT statement to cause INFORMIX-4GL to finishprocessing a report.

SyntaxFINISH REPORT report-name

ExplanationFINISH REPORT are required keywords.

report-name is the identifier of a report.

NoteYou must use the FINISH REPORT statement to let INFORMIX-4GL know thatno more statements are to be included in the report processing.

ExampleFINISH REPORT cust_ords

Related StatementsOUTPUT TO REPORT, START REPORT

INFORMIX-4GL Statement Syntax 7-101

Page 468: Manual Informix

FLUSH

FLUSH

OverviewUse the FLUSH statement to force INFORMIX-4GL to insert the buffered rowsinto the database without closing the cursor.

SyntaxFLUSH cursor-name

ExplanationFLUSH is a required keyword.

cursor-name is the name of a cursor that has been DECLAREd for anINSERT statement.

Notes1. The global variables status (whose value is taken from SQLCA.SQLCODE)

and SQLCA.SQLERRD[3] indicate the result of each FLUSH statement. IfINFORMIX-4GL successfully inserts all the buffered rows into the data-base, it sets status to zero and sets SQLCA.SQLERRD[3] to the number ofrows inserted. If INFORMIX-4GL is unsuccessful in its attempt to insertthe rows into the database, it sets status to a negative number (specifi-cally, the number of the error message) and sets SQLCA.SQLERRD[3] to thenumber of rows successfully inserted into the database.

2. You can use the FLUSH statement to force the insertion. You cannot delayinsertion by not using the FLUSH statement. INFORMIX-4GL automati-cally flushes the buffer when it is full.

3. Insert cursors that contain only constants in the values clause are not buff-ered. INFORMIX-4GL keeps a count of the number of rows to be insertedinto the database, and the database is updated only when you issue aFLUSH or CLOSE statement.

4. If you exit a program without closing the cursor, the buffer is leftunflushed. Rows inserted into the buffer and remaining since the lastflush are lost. Do not expect the end of program to close the cursor andflush the buffer.

7-102 INFORMIX-4GL Statement Syntax

Page 469: Manual Informix

FLUSH

ExampleFLUSH icurs

Related StatementsCLOSE, DECLARE, OPEN, PUT

INFORMIX-4GL Statement Syntax 7-103

Page 470: Manual Informix

FOR

FOR

OverviewUse the FOR statement to cause a sequence of statements to be executed aspecified number of times.

SyntaxFOR integer-var = integer-expr TO integer-expr

[STEP integer-expr]statement...[CONTINUE FOR]...[EXIT FOR]...

END FOR

ExplanationFOR is a required keyword.

integer-var is a program variable of type INTEGER or SMALLINT thatserves as a counter.

integer-expr is an expression that evaluates to an INTEGER or a SMALL-INT.

TO is a required keyword.

STEP is an optional keyword.

statement is an INFORMIX-4GL statement.

CONTINUE FOR is an optional statement.

EXIT FOR is an optional statement.

END FOR are required keywords.

7-104 INFORMIX-4GL Statement Syntax

Page 471: Manual Informix

FOR

Notes1. 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 secondinteger-expr in STEPs of the third integer-expr. The default STEP is 1.

2. The CONTINUE FOR statement interrupts the sequence and causes theprogram control to return to the top of the sequence and to increment andtest the counter integer-var.

3. The EXIT FOR statement interrupts the sequence and causes the programcontrol 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 STEPvalue is positive, none of the statements up to END FOR is executed.

5. The STEP value may be negative.

ExampleDEFINE order_total MONEY(8),

i INTEGER

LET order_total = 0.00FOR i = 1 TO ARR_COUNT()

LET order_total = order_total+ p_items[i].total_price

END FOR

Related StatementsCONTINUE, EXIT, FOREACH, WHILE

INFORMIX-4GL Statement Syntax 7-105

Page 472: Manual Informix

FOREACH

FOREACH

OverviewUse the FOREACH statement to cause a sequence of statements to be executedfor each row returned from a query.

SyntaxFOREACH cursor-name [INTO variable-list]

statement...[CONTINUE FOREACH]...[EXIT FOREACH]...

END FOREACH

ExplanationFOREACH is a required keyword.

cursor-name is the name of a cursor that previously wasDECLAREd.

INTO is an optional keyword.

variable-list is a list of one or more program variables, separatedby commas.

CONTINUE FOREACH is an optional statement.

EXIT FOREACH is an optional statement.

END FOREACH are required keywords.

7-106 INFORMIX-4GL Statement Syntax

Page 473: Manual Informix

FOREACH

Notes1. The FOREACH statement repeats the sequence of statements up to END

FOREACH for each row returned by the query associated with cursor-name. The FOREACH statement OPENs the cursor and performs succes-sive 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 SELECTstatement associated with cursor-name, and vice versa. It lists the variablesinto which INFORMIX-4GL places the values returned by the query.

3. When FETCHing into a program array, you must place the INTO clause onthe FOREACH statement and not on the SELECT-statement of a DECLAREstatement.

4. The CONTINUE FOREACH statement interrupts the sequence and causesprogram control to return to the top of the sequence and to FETCH thenext row of the query.

5. The EXIT FOREACH statement interrupts the sequence and causes pro-gram control to jump to the first statement following the END FOREACHkeywords.

6. If the query returns no rows, none of the statements up to the ENDFOREACH is executed, and program control passes immediately to thefirst statement following END FOREACH. If you need to know whetherany rows were returned, you can set up a flag or a counter as in the exam-ple that follows these notes.

7. The FOREACH statement performs an implied OPEN statement. You can-not use the FOREACH statement if the OPEN statement must have a USINGclause to define unknown parameters in the SELECT statement.

8. If your database has transactions, the FOREACH statement must appearinside a transaction.

9. If, within the FOREACH statement, the WHENEVER NOT FOUND state-ment evaluates to TRUE, the open cursor is automatically closed.

INFORMIX-4GL Statement Syntax 7-107

Page 474: Manual Informix

FOREACH

ExamplePROMPT "Enter cut-off date for query: "

FOR o_date

DECLARE q_curs CURSOR FORSELECT order_num, o.customer_num, company

FROM orders o, customer cWHERE o.customer_num = c.customer_num

AND order_date < o_date

LET counter = 0

FOREACH q_curs INTO ord_num, cust_num, compLET counter = counter + 1CALL scan(ord_num, cust_num, comp)

END FOREACH

IF counte r = 0 THENERROR "No orders before ", o_date

END IF

Related StatementsCONTINUE, EXIT, FETCH, FOR, OPEN, WHILE, WHENEVER

7-108 INFORMIX-4GL Statement Syntax

Page 475: Manual Informix

FREE ( O )

FREE ( O )

OverviewThe FREE statement releases database engine resources allocated to aPREPAREd statement or to an OPENed and CLOSEd cursor.

SyntaxFREE { statement-id | cursor-name }

ExplanationFREE is a required keyword.

statement-id is the name of a statement that has been PREPAREd.

cursor-name is the name of a cursor whose DECLARE statement includesthe keywords SELECT or INSERT.

Notes1. 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 isautomatically PREPAREd when you OPEN the cursor. The statement hasno programmer-assigned statement-id. To release engine resources fromthat statement, use FREE cursor-name. Afterward, you cannot use the cur-sor unless you OPEN it again.

3. Do not FREE a cursor-name that was DECLAREd FOR statement-id. Useinstead FREE statement-id.

ExamplesFREE query_2FREE scurs

INFORMIX-4GL Statement Syntax 7-109

Page 476: Manual Informix

FUNCTION

FUNCTION

OverviewUse the FUNCTION statement to define a function.

SyntaxFUNCTION function-name ( [ argument-list ] )

statement. . .[ RETURN expr-list ]. . .

END FUNCTION

ExplanationFUNCTION is a required keyword.

function-name is a program identifier for the name of the function.

(argument-list) is a list (enclosed in parentheses) of one or more variables,separated by commas.

statement is an INFORMIX-4GL statement.

RETURN is an optional keyword that causes program control toreturn to the calling program.

expr-list is a list of zero or more expressions that yield the valuesreturned by function-name.

END FUNCTION are required keywords that terminate the FUNCTIONstatement.

Notes1. All arguments are passed by value.

2. You must DEFINE the arguments to the function, as well as other variablesused locally within the function.

7-110 INFORMIX-4GL Statement Syntax

Page 477: Manual Informix

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 namethat you define within the FUNCTION routine. Thus you call the followingfunction 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 inplace 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 theRETURNING clause of the CALL statement that calls the function.

7. The function-name must conform to the rules for 4GL identifiers, asdescribed in Chapter 2. An error results if function-name is the same as theidentifier of a global variable or of another function in the same program.

Related StatementCALL

INFORMIX-4GL Statement Syntax 7-111

Page 478: Manual Informix

GLOBALS

7

GLOBALS

OverviewUse the GLOBALS statement to DEFINE one or more variables to be globalvariables or to refer to the file where global variables are DEFINEd.

SyntaxGLOBALS {‘‘filename’’ |

DEFINE-statement...

END GLOBALS}

ExplanationGLOBALS is a required keyword.

filename is the pathname of the file where the global variablesare defined.

DEFINE-statement is a DEFINE statement for the global variable.

END GLOBALS are required keywords that terminate the GLOBALSstatement when variables are DEFINEd.

Notes1. 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 containingthe MAIN program block.

2. The GLOBALS filename statement must occur earlier in every file than anyfunction that makes reference to a global variable.

3. The GLOBALS statement must lie outside the MAIN program block andany FUNCTION or REPORT routines.

4. If any global variable is DEFINEd LIKE a database column, the DATABASEstatement naming the database must precede the GLOBALS statement.

-112 INFORMIX-4GL Statement Syntax

Page 479: Manual Informix

GLOBALS

ExamplesDATABASE storesGLOBALS

DEFINE p_customer RECORD LIKE customer.*...

END GLOBALS

GLOBALS "d4_globals.4gl"

Related StatementDEFINE

INFORMIX-4GL Statement Syntax 7-113

Page 480: Manual Informix

GOTO

GOTO

OverviewUse the GOTO statement to transfer program control unconditionally to adesignated point.

SyntaxGOTO [ : ]label-id

ExplanationGOTO is a required keyword.

: is an optional prefix to label-id and conforms to the ANSI standardfor SQL syntax.

label-id is a 4GL identifier.

Notes1. After a GOTO label-id statement successfully executes, program control is

transferred to the statement that follows LABEL label-id:. See the syntax ofthe 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 ofa FUNCTION or a REPORT with a GOTO statement.

Related StatementsLABEL, WHENEVER

7-114 INFORMIX-4GL Statement Syntax

Page 481: Manual Informix

GRANT

GRANT

OverviewUse the GRANT statement to specify user access privileges to a database or tothe tables and views in a database.

SyntaxGRANT tab-privilege ON table-name TO { PUBLIC | user-list }

[ WITH GRANT OPTION ] [ AS grantor ]

GRANT db-privilege TO { PUBLIC | user-list }

ExplanationGRANT is a required keyword.

tab-privilege is one or more of the following table-level access types (mul-tiple privileges must be separated by commas):

ALTER Add or delete columns or modify data typesof columns.

DELETE Delete rows.

INDEX Create indexes.

INSERT Insert rows.

SELECT [(cols)] Retrieve data from specified columns.

UPDATE [(cols)] Change values in specified columns.

ALL[ PRIVILEGES ]

of the above access types.

SELECT and UPDATE take column names asarguments, allowing you to specify col-umns that the user may select or update.Separate column names with commas.

The keyword PRIVILEGES following ALL isoptional.

ON is a required keyword.

table-name is the name of the table or view for which you are grantingaccess privileges.

TO is a required keyword.

INFORMIX-4GL Statement Syntax 7-115

Page 482: Manual Informix

GRANT

PUBLIC is the keyword that you use to specify access privileges forall users.

user-list is a list of login names for the users to whom you are grant-ing access privileges. You can enter one login name or aseries of login names, separated by commas.

WITH GRANTOPTION

are optional keywords.

AS is an optional keyword.

grantor is the username of the user issuing the GRANT statement.

db-privilege is one of the following database-level access types:

CONNECT Allows access to database tables without per-mission to create permanent tables andindexes.

RESOURCE Allows access to database tables with permis-sion to create permanent tables and indexes.

DBA Allows full database administrator privileges.

Notes1. 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 columnsfrom which the view is derived.)

3. The RESOURCE privilege includes the CONNECT privilege and adds thepermission 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 INFOR-MIX also has permission to alter the system catalogs.

• Permission to grant and revoke CONNECT, RESOURCE, and DBA priv-ileges to and from other users.

5. When you create a database, you are the Database Administrator andhave DBA privileges.

6. A DBA can use the AS keyword to grant table-level privileges on behalf ofanother user.

7-116 INFORMIX-4GL Statement Syntax

Page 483: Manual Informix

GRANT

7. You can grant privileges only on tables or views that you create, or ontables or views for which you have been given the GRANT OPTION.

8. When you use the WITH GRANT OPTION phrase to GRANT table-levelprivileges to another user, you give that user the power to GRANT thesame privileges to another user.

9. If you do not specify one or more column names, the SELECT or UPDATEaccess 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, ifyou grant RESOURCE privileges to a user but do not grant INDEX privi-leges 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 simpleview. You can grant SELECT privilege on a simple or complex view.

ExamplesThe following statements grant all table-level privileges (except ALTER) to allusers 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-levelprivileges except ALTER are automatically granted to all users (PUBLIC). Torestrict access privileges at the table level, you must revoke all privileges andgrant those that you want:

REVOKE ALL ON customer FROM PUBLIC

GRANT ALL ON customer TO joe, maryGRANT 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 StatementREVOKE

INFORMIX-4GL Statement Syntax 7-117

Page 484: Manual Informix

IF

IF

OverviewUse the IF statement to execute one or more statements conditionally.

SyntaxIF Boolean-expr

THENstatement. . .[ ELSEstatement. . . ]

END IF

ExplanationIF is a required keyword.

Boolean-expr is an expression that can be TRUE or FALSE.

THEN is a required keyword.

statement is any INFORMIX-4GL statement, including another IFstatement.

ELSE is an optional keyword.

END IF are required keywords.

Notes1. 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 anoptional ELSE (if present) or to END IF (if there is no ELSE) are skipped. Ifan ELSE is present, the statements following the ELSE are executed.

3. If Bool-expr evaluates as UNKNOWN because the expression contains NULLvalues, the IF statement behaves as though it were FALSE.

7-118 INFORMIX-4GL Statement Syntax

Page 485: Manual Informix

IF

ExampleIF p_index <= 1 THEN

ERROR "No more stock items in this direction"ELSE

LET p_index = p_index - 1DISPLAY dp_stock[p_index].* TO s_stock.*

END IF

Related StatementsCASE, WHENEVER

INFORMIX-4GL Statement Syntax 7-119

Page 486: Manual Informix

INITIALIZE

INITIALIZE

OverviewUse the INITIALIZE statement to initialize a program variable.

SyntaxINITIALIZE variable-list { LIKE column-list | TO NULL }

ExplanationINITIALIZE is a required keyword.

variable-list is a list of one or more variables, separated by commas.

LIKE is an optional keyword.

column-list is a list of column names, preceded by table names and sep-arated by commas.

TO NULL are optional keywords to assign NULL values.

Notes1. 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 ofthe table (owner. table-name). You must specify owner when you refer to atable owned by another user. The use of the prefix owner is optional in anon-MODE ANSI database. INFORMIX-4GL does check the accuracy ofowner, however, if you include it in a statement. See the section “OwnerNaming” in Chapter 3 for more information.

4. You can use the upscol utility to create and update the values insyscolval. (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 allusers. The INITIALIZE statement assigns to individual variables invariable-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 vari-ables that correspond to columns in tables owned by the specified user. If

7-120 INFORMIX-4GL Statement Syntax

Page 487: Manual Informix

INITIALIZE

no owner name is specified, and the user compiling the program ownsthe table, INFORMIX-4GL uses the values in the syscolval table owned bythat user.

7. If any columns corresponding to components of variable-list have not beenassigned DEFAULT values in syscolval, INFORMIX-4GL substitutes NULLvalues.

8. Since upscol does not support DATETIME or INTERVAL values, these datatypes 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 NULLvalue for each variable.

ExamplesINITIALIZE var1, var2, var3

LIKE tab1.col1, tab1.col2, tab1.col3

INITIALIZE v_cust.* LIKE customer.*

INITIALIZE v_orders.* TO NULL

INITIALIZE var1, var2, var3LIKE tab1.var1, eileen.tab2.var2, fred.tab3.var3

Related StatementsLET, VALIDATE

INFORMIX-4GL Statement Syntax 7-121

Page 488: Manual Informix

INPUT

INPUT

OverviewUse the INPUT statement to assign values to program variables from data thatthe user enters into fields of a screen form.

SyntaxINPUT { 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 ]

ExplanationINPUT is a required keyword. The INPUT statement allows the user

to change the data displayed on the screen.

BY NAME are keywords instructing INFORMIX-4GL to match names ofvariables to screen field names.

variable-list is a list of program variables to display.

WITHOUTDEFAULTS

are keywords to display on the screen the current values invariable-list.

FROM is a keyword to specify the screen fields whose values will beassigned to variable-list.

field-list is a list of one or more names of screen fields.

screen-record is the identifier of a collection of field names defined in aform specification as a SCREEN RECORD.

[ n ] is an integer, enclosed in brackets, to specify the row of ascreen array (beginning with line 1).

7-122 INFORMIX-4GL Statement Syntax

Page 489: Manual Informix

INPUT

ATTRIBUTE is a keyword to specify screen input attributes.

(attribute-list) is a list (in parentheses) of screen attributes.

HELP is a keyword to specify a help message.

help-number is an integer to identify a help message for this INPUT state-ment in the help file that was specified in the OPTIONSstatement.

BEFORE FIELD are keywords to transfer control to a 4GL statement when thecursor enters a field in the field-sublist.

field-sublist is a list of one or more of the fields either explicitly or implic-itly referenced in the INPUT statement.

AFTER FIELD are keywords to transfer control to a 4GL statement when thecursor leaves a field in the field-sublist.

AFTER INPUT are keywords to transfer control to a 4GL statement when theuser has finished entering input.

ON KEY are keywords to specify keys of the keyboard.

(key-list) is a list (in parentheses) of key designation(s), usually offunction or CTRL keys. If one of these is pressed duringinput, a 4GL statement is executed.

statement is a 4GL statement. It is executed during input, if BEFOREFIELD, AFTER FIELD, or ON KEY clause conditions are satis-fied. It is executed after input, if an AFTER INPUT clause isused.

NEXT FIELD are keywords that cause INFORMIX-4GL to move the cursorimmediately to a specified field.

field-name identifies a field from field-list or screen-record (or implied bythe BY NAME clause).

EXIT INPUT are keywords that direct INFORMIX-4GL to leave the INPUTstatement immediately.

END INPUT are keywords that terminate the INPUT statement. Thesekeywords are required if you include a BEFORE clause,AFTER clause, or ON KEY clause.

INFORMIX-4GL Statement Syntax 7-123

Page 490: Manual Informix

INPUT

Notes1. When you execute the INPUT statement with the WITHOUT DEFAULTS

clause, INFORMIX-4GL displays the current values of variable-list in thescreen fields. This option is appropriate when you are requesting inputprior to updating an existing row of a table.

2. If an INPUT statement omits the WITHOUT DEFAULTS clause, INFOR-MIX-4GL displays on the form the default values from the formspecification (or from syscolval, if no default valuess were specified bythe DEFAULT attribute in the form specification) and initializes the vari-ables in variable-list accordingly. INFORMIX-4GL assigns NULL values toall variables for which no default has been set. This option is appropriatewhen 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 identityof the program variable name and the screen field name. INFORMIX-4GLuses only the suffix portion of the name of the program variable and thescreen field. You must use the FROM option if the suffixes are not uniqueand unambiguous.

4. If you use the FROM option, the number of variables in variable-list mustbe the same as the number of field names in field-list or screen-record, andof the corresponding data type.

5. INPUT is terminated when the user presses ESCAPE (or the key specifiedas the Accept key in the OPTIONS statement). For single-item INPUTs (orafter the last item of multiple-item INPUTs), a RETURN is equivalent topressing the Accept key.

You can use the AFTER FIELD clause on the last field to override the ter-minating power of the RETURN by setting NEXT FIELD to the first field.This option wraps the field-list into a loop. Alternatively, use the INPUTWRAP option in the OPTIONS statement for the same effect.

6. The user triggers the AFTER INPUT clause (and the set of statements thatfollow that clause) by attempting to terminate the INPUT statement. (Seethe previous note.) If there is an AFTER INPUT clause, program controlpasses to the statements following that clause, rather than to the state-ments following the END INPUT clause. This feature allows theprogrammer to perform data validity checks before allowing the INPUTstatement to terminate.

7. INFORMIX-4GL passes control to the statements following a BEFOREclause when the cursor enters a field in field-list. It passes control to thestatements following an AFTER clause when the cursor leaves a field infield-list (after the user has pressed RETURN, indicating that data has been

7-124 INFORMIX-4GL Statement Syntax

Page 491: Manual Informix

INPUT

entered into the field). It passes control to the statements following an ONKEY clause after the user presses a key in key-list.

8. If there is no NEXT FIELD statement in the sequence of statements follow-ing a BEFORE or AFTER clause, the cursor moves to the next field in thedirection 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 executesthe statements in the ON KEY clause. It preserves the input buffer contain-ing the characters that the user typed before triggering the ON KEY clauseand restores them when the ON KEY clause returns. It resumes the inputin the same field with the cursor at the end of the buffered list of charac-ters. If you want to use the ON KEY clause to fill the field with anothervalue, be sure to move to a new field with the NEXT FIELD statement toprevent the INPUT statement from ignoring the new value.

10. The notation for function keys is F1 through F36 . The notation for CON-TROL 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 Interruptkey is INTERRUPT. Appendix I, “Modifying termcap and terminfo,”describes how to verify that the termcap and terminfo entries for yourterminal allow INFORMIX-4GL to recognize function keys.

11. By default, both ESCAPE and Interrupt are exits from the INPUT state-ment. If the DEFER INTERRUPT statement has been executed, an Interruptcauses INFORMIX-4GL to set the global variable int_flag to nonzero andterminate the INPUT statement (unless the function of Interrupt is rede-fined in an ON KEY clause). Otherwise, Interrupt immediately stops theprogram.

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 theOPTIONS statement.

• Interrupt, if you have executed a DEFER INTERRUPT statement. (Whenthe user presses the Interrupt key under these conditions, INFOR-MIX-4GL executes the statements in the ON KEY clause and setsint_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 keysare reserved for editing functions in the INPUT statement.

• Other keys that may have special meaning on your system, such asCTRL-S for XOFF.

13. Use of CTRL-I and CTRL-J in a key-list can conflict with normal data entry.

INFORMIX-4GL Statement Syntax 7-125

Page 492: Manual Informix

INPUT

14. In addition to the RETURN, ESCAPE, Interrupt, and Arrow keys, the usercan employ the following keys for editing during an INPUT statement:

CTRL-A toggles between insert and typeover mode.

CTRL-D deletes characters from the current cursor position to the endof the field.

CTRL-H moves the cursor nondestructively one space to the leftinside a field. It is equivalent to pressing the [ ←] key.

CTRL-L moves the cursor nondestructively one space to the rightinside a field. It is equivalent to pressing the [→] key.

CTRL-R redisplays the screen.

CTRL-X deletes the character beneath the cursor.

15. Function infield(field) from the function library returns TRUE if the cur-rent field is field, and FALSE otherwise. Use it to make field-dependentresponses when the user presses a key specified in the key-list of an ONKEY clause. If you call infield(field) outside the INPUT statement, it returnsa value corresponding to the field that was current when INPUT wasterminated.

16. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within theBEFORE, AFTER, or ON KEY clauses of an INPUT statement. You can, how-ever, call a function that executes one of these statements.

17. If you do not use the ATTRIBUTE clause, the display attributes of the inputfields are governed by the INPUT ATTRIBUTE clause of the most recentOPTIONS statement. (The description of the OPTIONS statement lists theorder of precedence among different sources of 4GL screen attributespecifications.)

18. In an INPUT statement, any screen attributes specified in attribute-listapply to all the fields in field-list or screen-record.

19. If you use the ATTRIBUTE clause, no default attributes in syscolatt orin the form specification file for fields in field-list or screen-record apply(including any default values from the DEFAULT attribute). Theattribute-list temporarily overrides any attributes specified in anOPTIONS, DISPLAY FORM, or OPEN WINDOW statement for these fields.

7-126 INFORMIX-4GL Statement Syntax

Page 493: Manual Informix

INPUT

20. These keywords can appear in the ATTRIBUTE clause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

You can specify zero or one of the keywords in the left-hand columns, andfrom zero to three from the right-hand column (but some terminals maynot support some combinations). On color terminals, NORMAL is inter-preted 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 onmonochrome terminals of keywords that specify color.

These keywords cannot produce the effects suggested by their namesunless the termcap or terminfo files and the physical terminals supportthe attribute. (See Appendix I, “Modifying termcap and terminfo.”)

Note: Some terminal entries in termcap or terminfo include the sg#1 orxmc#1 capabilities. On these terminals, the first character of variable-list isreplaced 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, INFOR-MIX-4GL does not support attributes that specify colors, and the onlyvalid attribute-list keywords are REVERSE and UNDERLINE.

INFORMIX-4GL Statement Syntax 7-127

Page 494: Manual Informix

INPUT

ExampleINPUT p_addr.* FROM sc_addr.*

ATTRIBUTE (REVERSE RED)HELP 101BEFORE 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.cityNEXT FIELD zipcode

END IFON KEY (F1)

IF infield(city) THENLET p_addr.city = "San Francisco"DISPLAY p_addr.city TO cityLET p_addr.state = "CA"DISPLAY p_addr.state TO stateNEXT FIELD zipcode

END IFEND INPUT

Related StatementsDISPLAY, DISPLAY FORM, EXIT, INPUT ARRAY, OPTIONS

7-128 INFORMIX-4GL Statement Syntax

Page 495: Manual Informix

INPUT ARRAY

INPUT ARRAY

OverviewUse the INPUT ARRAY statement to permit the user to enter data onto a screenarray and to store the data in a program record array.

SyntaxINPUT 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 ]

ExplanationINPUT ARRAY are required keywords.

record-array is a program array name. Usually, record-array is an array ofrecords.

WITHOUTDEFAULTS

are optional keywords to display the current values ofrecord-array.

FROM is a required keyword.

screen-array is the name of a screen record that corresponds to the fieldsin a row of a screen array.

HELP is an optional keyword.

help-number is an integer that identifies the help message for this INPUTARRAY statement in the help file set in the OPTIONSstatement.

ATTRIBUTE is a keyword to specify screen input attributes.

(attribute-list) is a list (in parentheses) of screen attributes.

INFORMIX-4GL Statement Syntax 7-129

Page 496: Manual Informix

INPUT ARRAY

BEFORE is an optional keyword.

ROW is an optional keyword.

INSERT is an optional keyword.

DELETE is an optional keyword.

FIELD is an optional keyword.

field-sublist is a list of one or more fields taken from screen-array.*.

AFTER is an optional keyword.

INPUT is an optional keyword.

ON KEY are optional keywords.

key-list is usually a list of one or more function or CTRL key designa-tions. The list can also include ESCAPE (if you have specifiedanother key as the Accept key in the OPTIONS statement) orInterrupt (if you have executed a DEFER INTERRUPT state-ment).

statement is any INFORMIX-4GL statement.

NEXT FIELD is an optional statement that causes the cursor to moveimmediately to the next field.

field-name is a field name to which the cursor should move.

EXIT INPUT is an optional statement directing INFORMIX-4GL to leavethe INPUT ARRAY statement immediately.

END INPUT is a statement that terminates an INPUT ARRAY statement. Itis required only when a BEFORE, an AFTER, or an ON KEYclause is used.

Notes1. When you execute the INPUT ARRAY statement with the WITHOUT

DEFAULTS clause, INFORMIX-4GL displays in screen-array the values inrecord-array. You must call set_count() with the number of rows inprogram-array before the INPUT ARRAY statement. (See a later note for thedefinition of set_count().) This is appropriate when you are requestinginput prior to updating an existing row of a table.

2. When you execute the INPUT ARRAY statement omitting the WITHOUTDEFAULTS clause, INFORMIX-4GL initializes the first row of screen-arrayand record-array with the default values from the form specification (orfrom syscolval if no defaults were set in the form). INFORMIX-4GLassigns 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 ini-

7-130 INFORMIX-4GL Statement Syntax

Page 497: Manual Informix

INPUT ARRAY

tializes that line and the corresponding row of record-array. This isappropriate when you are requesting input prior to inserting new rows ina table.

3. The user can insert rows into the middle of existing rows of record-arrayby pressing the Insert key (the default is the [ F1 ] function key. You canalter the default with the OPTIONS statement). The user can insert rows atthe 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 record-array, INFORMIX-4GL displays a message that the array is full.

5. The user can delete the current row and move the following rows up tofill the gap by pressing the [ F2 ] function key. You can alter this defaultwith the OPTIONS statement.

6. The user can move the cursor and scroll the displayed rows using theArrow keys and the function keys [ F3 ] and [ F4 ].

RIGHT ARROW moves the cursor non-destructively (does not blankout the current contents) one space to the right insidea screen field. At the end of the screen field, it causesa jump to the first character position of the next screenfield.

LEFT ARROW moves the cursor non-destructively one space to theleft inside a screen field. At the end of the screen field,it causes a jump to the first character position of theprevious screen field.

DOWN ARROW moves the cursor down one row on the screen. If thecursor was on the last row of the screen array beforethe user pressed [ ↓ ], the displayed data moves upone row.

UP ARROW moves the cursor up one row on the screen. If the cur-sor was on the first row before the user pressed [ ↑ ],the displayed data moves down one row. If the firstprogram array row is already on the first screen arrayrow, [ ↑ ] does nothing.

F3 scrolls the display to the next full page of programarray rows. You can reset this key using the OPTIONSstatement.

F4 scrolls the display to the previous full page of pro-gram array rows. You can reset this key using theOPTIONS statement.

INFORMIX-4GL Statement Syntax 7-131

Page 498: Manual Informix

INPUT ARRAY

7. The INPUT ARRAY statement is terminated when the user enters ESC orthe key you specified as the Accept key in the OPTIONS statement. If thereis an AFTER INPUT clause, the program control passes to the statementsfollowing that clause, rather than to the statements following the ENDINPUT clause. This feature allows the programmer to perform data valid-ity checks before allowing the INPUT ARRAY statement to terminate.Unlike the INPUT statement, the RETURN does not terminate thestatement.

8. The number of variables in a row of record-array must be the same as thenumber of fields in a row of screen-array and of the corresponding datatype.

9. INFORMIX-4GL executes BEFORE, AFTER, and ON KEY clauses in the fol-lowing order:

BEFORE ROWBEFORE INSERT, DELETEBEFORE FIELDON KEYAFTER FIELDAFTER INSERT, DELETEAFTER ROWAFTER INPUT

10. INFORMIX-4GL passes control to the statements following a BEFORE ROWclause 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 BEFOREINSERT 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 BEFOREDELETE clause when the user presses the Delete key ([ F2 ]).

13. INFORMIX-4GL passes control to the statements following a BEFOREFIELD clause when the cursor enters a field.

14. INFORMIX-4GL passes control to the statements following an ON KEYclause when the user presses a key named in key-list.

15. INFORMIX-4GL passes control to the statements following an AFTERFIELD clause when the cursor leaves a field.

7-132 INFORMIX-4GL Statement Syntax

Page 499: Manual Informix

INPUT ARRAY

16. INFORMIX-4GL passes control to the statements following an AFTERINSERT clause when the user inserts a row and leaves it (without neces-sarily entering data into it).

17. INFORMIX-4GL passes control to the statements following an AFTERDELETE clause when the user presses the Delete key ([ F2 ]) and the rowhas been deleted.

18. INFORMIX-4GL passes control to the statements following an AFTER ROWclause when

• The cursor leaves the row by any means.

• An INSERT is complete.

19. INFORMIX-4GL passes control to the statements following an AFTERINPUT clause when the user presses ESC or the key specified as the Acceptkey in the OPTIONS statement.

20. If there is no NEXT FIELD statement in the sequence of statements follow-ing a BEFORE or AFTER clause, the cursor moves to the next field in thedirection that the user indicated (forward for [ → ] or RETURN and back-ward 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 executesthe statements in the ON KEY clause. It preserves the input buffer thatcontains the characters the user typed before triggering the ON KEYclause, restores them when the ON KEY clause returns, and resumes theinput in the same field with the cursor at the end of the buffered list ofcharacters. If you want to use the ON KEY clause to fill the field withanother value, be sure to move to a new field with the NEXT FIELD state-ment to prevent the INPUT ARRAY statement from ignoring the newvalue.

22. The notation for function keys is F1 through F36 . The notation for CTRLkeys is CONTROL-key, where key is any letter except A, D, H, L, R, or X. Thenotation for ESCAPE is ESCAPE or ESC. The notation for the Interrupt keyis INTERRUPT.

Appendix I, “Modifying termcap and terminfo,” describes how to verifythat the termcap and terminfo entries for your terminal allow INFOR-MIX-4GL to recognize function keys.

23. By default, both ESCAPE and Interrupt are exits from the INPUT ARRAYstatement. If the DEFER INTERRUPT statement has been executed, anInterrupt causes INFORMIX-4GL to set int_flag to nonzero and terminatethe INPUT ARRAY statement (unless the function of Interrupt has beenredefined in an ON KEY clause). Otherwise, an Interrupt causes an imme-diate program stop.

INFORMIX-4GL Statement Syntax 7-133

Page 500: Manual Informix

INPUT ARRAY

24. You can include the following keys in a key-list under the statedconditions:

• ESCAPE, if you have specified another key as the Accept key in theOPTIONS statement.

• [ F1 ] if you have specified another key as the Insert key in theOPTIONS statement.

• [ F2 ] if you have specified another key as the Delete key in theOPTIONS statement.

• [ F3 ] if you have specified another key as the Next key in the OPTIONSstatement.

• [ F4 ] if you have specified another key as the Previous key in theOPTIONS 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 andsets int_flag to nonzero, but does not terminate the INPUT ARRAYstatement.)

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 keysare 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 INPUTARRAY statement:

CTRL-A toggles between insert and typeover mode.

CTRL-D deletes characters from the current cursor position to the end ofthe field.

CTRL-H moves the cursor non-destructively one space to the left insidea field.

CTRL-L moves the cursor non-destructively one space to the rightinside a field.

CTRL-R redisplays the screen.

CTRL-X deletes the character beneath the cursor.

27. The function infield(field) from the function library returns TRUE if thecurrent field is field and FALSE otherwise. It can be used to make field-dependent responses when the user presses a key in the key-list of an

7-134 INFORMIX-4GL Statement Syntax

Page 501: Manual Informix

INPUT ARRAY

ON KEY clause. If you call infield(field) outside the INPUT ARRAY state-ment, it returns a value corresponding to the field that was current whenINPUT ARRAY was terminated.

28. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within theBEFORE, AFTER, or ON KEY clauses of an INPUT ARRAY statement. How-ever, 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 asfollows:

arr_curr( ) returns the current record-array row. This is the row wherethe cursor is at the beginning of the [ BEFORE | AFTER ]ROW block, not the row the cursor moves to after execu-tion of the block.

arr_count( ) returns the total number of filled rows in record-array.

scr_line( ) returns the current row of screen-array. The current row isdefined in the same way that the current row forarr_curr( ) is defined.

set_count( ) takes an argument that is the total number of filled rowsin record-array. You must call this function before execut-ing the INPUT ARRAY WITHOUT DEFAULTS, so that theprogram knows the initial value of arr_count( ).

30. If you do not use the ATTRIBUTE clause, the display attributes of the inputfields are governed by the INPUT ATTRIBUTE clause of the most recentOPTIONS statement. (The description of the OPTIONS statement lists theorder of precedence among different sources of 4GL screen attributespecifications.)

31. In an INPUT ARRAY statement, any screen attributes specified inattribute-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 insyscolatt or in the form specification file for fields in field-list orscreen-record apply (including any default values from the DEFAULTattribute). The attribute-list temporarily overrides any attributes specifiedin an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement for thesefields.

INFORMIX-4GL Statement Syntax 7-135

Page 502: Manual Informix

INPUT ARRAY

33. These keywords can appear in the ATTRIBUTE clause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

You can specify zero or one of the keywords in the left-hand columns, andfrom zero to three from the right-hand column (but some terminals maynot support some combinations). On color terminals, NORMAL is inter-preted 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 onmonochrome terminals of keywords that specify color.

These keywords cannot produce the effects suggested by their namesunless the termcap or terminfo files and the physical terminals supportthe attribute. (See Appendix I, “Modifying termcap and terminfo.”)

Note: Some terminal entries in termcap or terminfo include the sg#1 orxmc#1 capabilities. On these terminals, the first character of variable-list isreplaced 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 aftercolumn 1, if you specify display attributes.

34. On UNIX systems that use terminfo files rather than termcap, INFOR-MIX-4GL does not support attributes that specify colors, and the onlyvalid attribute-list keywords are REVERSE and UNDERLINE.

7-136 INFORMIX-4GL Statement Syntax

Page 503: Manual Informix

INPUT ARRAY

ExampleThe following program fragment assumes that one column of the screenarray (sc_array) contains the row number (row_num) of the program array(pa_array) being displayed there. The next column of sc_array is calledfirst_data. The program recalculates and displays the row number after theuser inserts new rows or deletes old ones.

DEFINE pa_total INTEGER # total number of rows# in program array

DEFINE pa_curr INTEGER # current program array# row number

DEFINE sc_curr INTEGER # current screen array# row number

DEFINE sc_total INTEGER # total number of rows# in screen array

DEFINE k SMALLINTINPUT ARRAY pa_array FROM sc_array.*

AFTER INSERT, DELETELET 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 = kIF sc_curr <= sc_total THEN

DISPLAY k TO sc_array[sc_curr].row_numLET sc_curr = sc_curr + 1

END IFEND FOR

END INPUT

Related StatementsDISPLAY ARRAY, EXIT, INPUT, OPTIONS

INFORMIX-4GL Statement Syntax 7-137

Page 504: Manual Informix

INSERT

INSERT

OverviewUse the INSERT statement to insert one or more new rows into an existingtable.

SyntaxINSERT INTO table-name [ ( column-list ) ]

{ VALUES ( value-list ) | SELECT-statement }

ExplanationINSERT INTO are required keywords.

table-name is the name of the table to which to add rows.

column-list is a list of the names of the columns into which to insertdata. You can enter one column name or a series of col-umn names, separated by commas.

VALUES is a keyword.

value-list are the values to insert into the columns that you speci-fied. You can enter one or more program variables or con-stants, separated by commas.

SELECT-statement is a valid SELECT statement.

Notes1. 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 youenter into the first listed column, the second value into the second listedcolumn, and so on.

2. Entering column names is optional. If you omit them, 4GL assumes thatthe values are listed in the order in which the columns are listed in thesyscolumns systems catalog. Unless you have subsequently used theALTER TABLE statement to change the order, the order is the same aswhen the table was created.

3. If you have previously defined a RECORD type program variable LIKEtable-name, you can use the program variable in place of a list of values inan INSERT statement.

7-138 INFORMIX-4GL Statement Syntax

Page 505: Manual Informix

INSERT

4. When you execute an INSERT statement, INFORMIX-4GL inserts a singlerow into the database (unless a SELECT statement appears after theVALUES clause). If you DECLARE a cursor for an INSERT statement anduse the OPEN, PUT, FLUSH, and CLOSE statements, INFORMIX-4GL buff-ers 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 thetable, 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 SELECTstatement.

8. Although the values that you insert do not have to be of the same datatype as the columns themselves, they must be compatible. You can insertonly CHAR data into CHAR columns, and only numbers or character rep-resentation of number data into number columns.

9. Enter a zero (0) for a SERIAL column in the INSERT statement if you want4GL to insert the next SERIAL value for the table. Enter a nonzero value fora SERIAL column that does not duplicate a value already in the table, ifyou want 4GL to use that value. An error occurs if you enter a nonzerovalue 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 INTERVALvalues.)

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 ROLL-BACK WORK statements.

13. Each row affected by the INSERT statement within a transaction is lockedfor the duration of the transaction; therefore, a single INSERT statementthat affects a large number of rows locks those rows until the entire oper-ation is completed. If the number of rows affected is very large, you mightexceed the limits that your operating system places on the maximumnumber of simultaneous locks. If this occurs, you may want either to

INFORMIX-4GL Statement Syntax 7-139

Page 506: Manual Informix

INSERT

reduce the scope of the INSERT statement or lock the entire table beforeexecuting the statement.

See the section “Locking” in Chapter 3 for a more detailed description oftable-level and row-level locking in INFORMIX-4GL.

Caution: 4GL makes every possible effort to perform data conversion, includingconverting the character string ‘‘123’’ into the integer 123 . If the data cannot be con-verted, however, INSERT stops. Unless you have created the database withtransactions, all changes made to that point remain, but subsequent rows from theSELECT statement will not be inserted. Data conversion also fails if the target datatype cannot hold the value offered. For example, you cannot insert the integer123456 into a SMALLINT.

ExamplesDEFINE 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 StatementsDECLARE, DELETE, SELECT

7-140 INFORMIX-4GL Statement Syntax

Page 507: Manual Informix

LABEL

LABEL

OverviewUse the LABEL statement to indicate the position in a 4GL program to whichthe GOTO statement transfers control.

SyntaxLABEL label-id:

ExplanationLABEL is a required keyword.

label-id: is an INFORMIX-4GL identifier, followed by a colon ( : ).

NoteThe LABEL statement must be in the same program block (MAIN, FUNCTION,or REPORT) as the GOTO statement with the same label-id. You cannot useGOTO to transfer out of a routine.

ExampleIF customer_nu m < 0 THEN

GOTO abortEND IFstatement...

LABEL abort:statement

Related StatementsGOTO, WHENEVER

INFORMIX-4GL Statement Syntax 7-141

Page 508: Manual Informix

LET

LET

OverviewUse the LET statement to assign a value to a program variable.

SyntaxLET variable = expr

ExplanationLET is a required keyword.variable is the identifier of a simple program variable.expr is an expression.

Notes1. 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 recordvariable from another record variable using the statement

LET x.* = y.*

This statement is shorthand for a sequence of LET statements assigning val-ues of elements of y to elements of x.

ExamplesLET a = b + c

LET d[index] = "This is a string"

LET newstr = mystr[2,6]

Related StatementINITIALIZE

7-142 INFORMIX-4GL Statement Syntax

Page 509: Manual Informix

LOAD

LOAD

OverviewUse the LOAD statement to fill an existing table with data taken from an ASCIIfile.

SyntaxLOAD FROM "pathname" [ DELIMITER "char" ]

{ INSERT INTO table-name [ ( column-name [ , . . . ] ) ]| INSERT-stmt }

ExplanationLOAD FROM are required keywords.

pathname is a character variable or constant that evaluates to the path-name of a file that contains rows of data.

DELIMITER is an optional keyword to indicate that the following charappears at the end of each data field in the file.

char is a CHAR variable or a quoted string containing exactly onecharacter.

INSERT INTO are keywords to specify where to store the data.

table-name is the identifier of an existing table.

column-name is a column name (in parentheses) in table-name.

INSERT-stmt is a character string or variable containing the text of anINSERT statement in the form shown here, with no VALUESclause or SELECT clause.

Notes1. You must have INSERT permission to use the LOAD statement.

2. You can specify an optional list of one or more column names, enclosedwithin parentheses and separated by commas.

3. Fields in the input file must be separated by a delimiter character. If youdo not specify a delimiter in the DELIMITER clause, INFORMIX-4GL

INFORMIX-4GL Statement Syntax 7-143

Page 510: Manual Informix

LOAD

checks the DBDELIMITER environment variable and uses this setting, if itexists. 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 interpre-tation as a field delimiter.

4. The LOAD statement can accept the format of data from a file written bythe UNLOAD statement (described later in this chapter).

5. The number of data fields in the load file must equal the number of col-umns 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 orderand data type of the columns specified in the database table. There mustbe exactly as many delimited fields in each line of the file as the numberof columns that you imply or specify in the INTO clause. The length ofeach data field must be less than or equal to the length specified for eachcolumn of the database table. The value in each field must be convertibleto the data type of the corresponding column.

7. See also “The dbload Utility,” described in Appendix E, which gives youmore options for the format of the input file.

8. A NULL column should be represented in the input file by no charactersbetween delimiters.

9. A blank CHAR column should be represented in the input file by one ormore blank characters between delimiters.

10. It is permissible to have leading blanks in number, DATE, and MONEYfields.

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 theformat of the DATE field is mm/dd/yy, the yy is interpreted as 19yy. Anyvalue in a DATE field must be a legal date (for example, February 30 isillegal).

12. MONEY fields can have leading currency symbols.

13. DATETIME and INTERVAL values must be in character form, showingonly 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 cor-responds to the qualifier associated with the column.

14. If your database has transactions but is not MODE ANSI, you must issue aBEGIN WORK statement before using LOAD.

15. LOAD appends new rows to the table, rather than overwriting existingdata.

7-144 INFORMIX-4GL Statement Syntax

Page 511: Manual Informix

LOAD

16. You cannot PREPARE a LOAD statement.

17. The embedded INSERT statement is restricted to the syntax shown hereand cannot include a VALUES clause or a SELECT statement.

18. When you execute a LOAD statement, INFORMIX-4GL sets status to zeroto indicate success, or to an error number to indicate failure. If an erroroccurs, the SQLCODE and SQLERRD[2] error codes are set, as described inChapter 3. In any case, the value of SQLERRD[3] is set to the number ofrows that LOAD inserted.

ExampleLOAD FROM "/a/data/ord.loadfile" DELIMITER ";"

INSERT INTO orders

LOAD FROM "/tmp/prices" DELIMITER ","INSERT INTO walter.worktab(price,discount)

Related StatementsUNLOAD, INSERT

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

INFORMIX-4GL Statement Syntax 7-145

Page 512: Manual Informix

LOCK TABLE

LOCK TABLE

OverviewUse the LOCK TABLE statement to control access to a table by other users.

SyntaxLOCK TABLE table-name IN { SHARE | EXCLUSIVE } MODE

ExplanationLOCK TABLE are required keywords.

table-name is the name of the table you want to lock.

IN is a required keyword.

SHARE is a keyword to give other users read access to the table, butto prevent them from modifying any of the data that itcontains.

EXCLUSIVE is a keyword to prevent other users from having any accessto the table.

MODE is a required keyword.

Notes1. 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 thattable in either mode until the first user unlocks it.

2. If your database has transactions and is not MODE ANSI, you must issuea BEGIN WORK statement before you can issue the LOCK TABLEstatement.

3. You can use the LOCK TABLE statement immediately after beginning atransaction to override row-level locking during the transaction. Nor-mally, each row of a table affected by a statement within a transaction islocked for the duration of the transaction. During transactions that affecta large number of rows, you can exceed the limit that your operating sys-tem 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

Page 513: Manual Informix

LOCK TABLE

this strategy when executing a transaction that affects a large number ofrows or every row in a table.

See the section “Locking” in Chapter 3 for more information about table-level and row-level locking in INFORMIX-4GL.

4. You cannot lock system catalogs. (See Appendix B for a list of systemcatalogs.)

ExampleLOCK TABLE orders IN EXCLUSIVE MODE

Related StatementsBEGIN WORK, COMMIT WORK, UNLOCK TABLE

INFORMIX-4GL Statement Syntax 7-147

Page 514: Manual Informix

MAIN

MAIN

OverviewUse the MAIN keyword to introduce the MAIN program block.

SyntaxMAIN

statement. . .

END MAIN

ExplanationMAIN is a required keyword.

statement is any INFORMIX-4GL statement except MAIN.

END MAIN are required keywords that terminate the MAIN programblock.

NoteEvery INFORMIX-4GL program must have a MAIN program block and canhave one or more functions and reports.

Related StatementsFUNCTION, REPORT

7-148 INFORMIX-4GL Statement Syntax

Page 515: Manual Informix

MENU

MENU

OverviewUse the MENU statement to create a menu screen, to define user menuoptions, to designate help numbers, and to define what statements should beexecuted for each option.

SyntaxMENU "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

ExplanationMENU is a required keyword.

menu-name is a character string giving the title of the menu.

COMMAND is a required keyword.

KEY is an optional keyword.

key-list is a list of one or more letters, function key identifiers,or CTRL key identifiers, separated by commas. You donot need to put quotation marks around single, print-able characters.

menu-option is a single-word label for a menu option. Themenu-option must be enclosed in quotation marks ( " ).

helpline is a one-line character string describing themenu-option. The helpline must be enclosed inquotation marks ( " ).

HELP is an optional keyword.

INFORMIX-4GL Statement Syntax 7-149

Page 516: Manual Informix

MENU

help-number is the number of the help message in the help file des-ignated in the OPTIONS statement that corresponds tomenu-option.

statement is an INFORMIX-4GL statement that you want executedwhen the user selects the preceding option. Severalstatements can exist for each option.

CONTINUE MENU is an optional statement that returns program controlto the current MENU statement.

EXIT MENU is an optional statement that causes program control tomove to the first statement following the END MENUkeywords.

NEXT OPTION are optional keywords that precede the menu optionthat you want highlighted when you return to themenu.

END MENU are required keywords that terminate the MENUstatement.

Notes1. 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 menu-options in the order of the COMMAND clauses.

3. When INFORMIX-4GL displays a menu, it adds a colon (:) and a spaceafter the menu name, as well as a space before and after each menuoption. If the width of the menu exceeds the number of characters that thescreen or a window can display on a single line, INFORMIX-4GL displaysthe first ‘‘page’’ of options followed by an ellipsis ( . . . ) indicating thatadditional options exist. For example,

menu-name: menu-option1 menu-option2 menu-option3 menu-option4 ...optional Help line

If the user presses the SPACEBAR or [ → ] key to move past the rightmostoption (menu-option4 in this case), INFORMIX-4GL displays the next

7-150 INFORMIX-4GL Statement Syntax

Page 517: Manual Informix

MENU

page of menu options. In the following example, the ellipses at each endindicate that more menu options exist in both directions.

menu-name: ... menu-option5 menu-option6 menu-option7 menu-option8 ...optional Help line

If the user moves the highlight to the right past menu-option8 in thisexample, INFORMIX-4GL displays a page of menu options like thefollowing:

menu-name: ... menu-option9 menu-option10 menu-option11optional Help line

Since no ellipsis appears to the right of the menu, the user has come to thelast page of the menu options. The user can display the previous page ofmenu options again by using the [ ← ] key to move the highlight past theleftmost option in the example. The user can display the first page ofmenu options by using the [ → ] key to move the highlight past the right-most 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 fileset by the OPTIONS statement.

5. A run-time error occurs if you specify a help-number for an option, andthat number does not occur in the help file, or if the help file does notexist.

6. You will incur a run-time error if the menu cannot fit on the screen or inthe current window.

INFORMIX-4GL Statement Syntax 7-151

Page 518: Manual Informix

MENU

7. INFORMIX-4GL truncates any helpline that exceeds the width of the screenor current window.

8. The user chooses an option by typing one of the letters in key-list. If theKEY clause is not present, the user chooses an option by typing the firstletter of menu-option.

9. After the user chooses an option, INFORMIX-4GL executes the statementsimmediately following the COMMAND clause.

10. After INFORMIX-4GL executes all the statements for an option, it redis-plays the menu, and the user can choose another option.

11. You can execute a CONTINUE MENU statement anywhere within thestatements following the COMMAND clause. Use of this statement causesthe 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 nota-tion 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-Zmight also not be allowed, depending on your implementation of theUNIX operating system.)

The key-list notation for the key is ESC or ESCAPE. The notation for theInterrupt key (often DEL or CTRL-C) is INTERRUPT.

13. Unless you use the KEY clause, the initial letters of each menu-optionshould be different, regardless of case. The values within the key-list mustbe unambiguous. Each option must be uniquely defined.

14. INFORMIX-4GL produces a run-time error if a menu option exceeds thelength of the screen or window.

15. You can add a ‘‘hidden’’ option to your menu by including a KEY key-listchoice in the list of menu COMMANDs. This is demonstrated in the fol-lowing example.

7-152 INFORMIX-4GL Statement Syntax

Page 519: Manual Informix

MENU

ExampleMENU "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 16EXIT PROGRAM

END MENU

These statements produce the following menu:

TOP LEVEL: Add Find Change Delete ExitAdd a row to the database

Related CommandOPTIONS

INFORMIX-4GL Statement Syntax 7-153

Page 520: Manual Informix

MESSAGE

MESSAGE

OverviewUse the MESSAGE statement to display a character string on the Message line.

SyntaxMESSAGE display-list [ ATTRIBUTE ( attribute-list ) ]

ExplanationMESSAGE is a required keyword.

display-list is a list of one or more program variables and/or string con-stants (enclosed in quotation marks), separated by commas.

ATTRIBUTE is an optional keyword.

attribute-list is a list of one or more screen attributes, separated bycommas.

Notes1. 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 inmenus. See the OPTIONS statement for information about resetting thisline to a different position.

3. The default attribute for the Message line is the NORMAL display. You canalter the default attribute with the ATTRIBUTE clause.

7-154 INFORMIX-4GL Statement Syntax

Page 521: Manual Informix

MESSAGE

4. The following list shows the screen attributes allowed in the ATTRIBUTEclause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIMas BLUE, and INVISIBLE as BLACK. If you have a colornames file, you canuse the color names listed there. (See Appendix I.)

ExampleMESSAGE "Enter the order data."

Related StatementsOPTIONS, PROMPT

INFORMIX-4GL Statement Syntax 7-155

Page 522: Manual Informix

OPEN

OPEN

OverviewUse the OPEN statement to establish search criteria for a SELECT cursor andinitialize the system for subsequent FETCHes, or to set up an INSERT bufferfor an INSERT cursor that references program variables.

SyntaxOPEN cursor-name [ USING variable-list ]

ExplanationOPEN is a required keyword.

cursor-name is the identifier of a previously declared cursor.

USING is a keyword, needed only if the cursor expects user-sup-plied search values.

variable-list is a list of program variables, separated by commas, corre-sponding to the ‘‘?’’ parameters in a query associated with aSELECT cursor.

Notes1. If cursor-name is associated with a SELECT statement, the OPEN statement

examines the content of the program variables and, using these values forthe parameters in the SELECT statement, establishes the search criteria fordetermining the logical set of rows that satisfies the WHERE clause. Thisset of rows is called the active set. It leaves the cursor in an open state andpointing before the first row of the active set.

2. The active set is a dynamic collection of rows; it is not fixed at the timewhen the OPEN statement is executed. Rows meeting the WHERE criteriaand qualified for FETCHing depend on the activity in the table.

3. Once the active set for a SELECT cursor is determined, the program vari-ables are not reexamined until you reopen the cursor.

4. If a SELECT cursor is already open, an OPEN statement closes the cursorand reopens it, creating a new active set, based on the current values ofthe program variables.

7-156 INFORMIX-4GL Statement Syntax

Page 523: Manual Informix

OPEN

5. The FOREACH statement performs an implied OPEN statement. You can-not use the FOREACH statement if the OPEN statement for a SELECTcursor must have a USING clause to supply values for ‘‘?’’ parameters ina PREPAREd SELECT statement.

6. If cursor-name is associated with an INSERT statement (rather than aSELECT statement), the OPEN statement cannot include a USING clause.

7. If you reopen an INSERT cursor that is already open, INFORMIX-4GLflushes the INSERT buffer (that is, INFORMIX-4GL inserts any rows cur-rently in the INSERT buffer into the database table). The global variableSQLCA. SQLERRD [3] is set to the number of rows successfully insertedinto the database.

8. A cursor declared FOR UPDATE is called an UPDATE cursor. In a databasethat uses transactions, you cannot OPEN an UPDATE cursor outside atransaction unless it also was declared WITH HOLD. You can OPEN a non-UPDATE cursor, or one declared WITH HOLD, at any time.

In a non-MODE ANSI database that has transactions, a transaction beginswith a BEGIN WORK statement and ends with a COMMIT WORK or ROLL-BACK WORK statement. In a MODE ANSI database, no BEGIN WORK isrequired; all actions take place inside transactions.

9. If you declare a cursor with a DECLARE statement that includes theSELECT or INSERT keywords, INFORMIX-4GL implicitly PREPAREs thestatement when you OPEN that cursor.

10. The database engine allocates resources to explicitly or implicitly PRE-PAREd statements. If you release resources with FREE cursor-name, youcannot use that cursor unless you OPEN it again. If you specify FREEstatement-id, you cannot OPEN a cursor that references statement-id unlessyou PREPARE that statement again.

ExamplesDECLARE s_curs CURSOR FOR

SELECT * FROM ordersOPEN s_curs

DECLARE q_cursor CURSOR FORSELECT o.order_num, SUM(total_price)FROM orders o, items iWHERE o.order_date > "06/04/86"

AND o.customer_num = 110AND o.order_num = i.order_num

GROUP BY o.order_numOPEN q_cursor

INFORMIX-4GL Statement Syntax 7-157

Page 524: Manual Informix

OPEN

Related StatementsCLOSE, DECLARE, FETCH, FLUSH, FOREACH, FREE, PREPARE, PUT

7-158 INFORMIX-4GL Statement Syntax

Page 525: Manual Informix

OPEN FORM

OPEN FORM

OverviewUse the OPEN FORM statement to associate an INFORMIX-4GL identifier witha pre-compiled screen form.

SyntaxOPEN FORM form-name FROM "form-file"

ExplanationOPEN FORM are required keywords.

form-name is an INFORMIX-4GL identifier.

FROM is a required keyword.

form-file is the pathname of a compiled screen form (omitting theextension .frm). form-file must be enclosed in quotationmarks.

Notes1. You must open a form before you can display it.

2. When you execute the OPEN FORM statement, the compiled form isloaded into and kept in memory until you execute a CLOSE FORM state-ment for that form. If you have displayed another form and wish to regainthe space used by the first form, you can execute CLOSE FORM on the oldform. The CLOSE FORM statement is a memory-management feature only;it does not affect the logic of the program.

ExampleOPEN FORM order_form FROM "orderform"

Related StatementsCLOSE FORM, DISPLAY FORM

INFORMIX-4GL Statement Syntax 7-159

Page 526: Manual Informix

OPEN WINDOW

OPEN WINDOW

OverviewUse the OPEN WINDOW statement to create and open a window at a specifiedorigin on the screen. This can optionally display a form.

SyntaxOPEN WINDOW window-name AT row, column

WITH { integer ROWS, integer COLUMNS | FORM "form-file" }[ ATTRIBUTE ( attribute-list ) ]

ExplanationOPEN WINDOW are required keywords.

window-name is the name of the window that you want to create.

AT is a required keyword.

row is an integer or integer variable between one and the max-imum number of lines allowed by your terminal (usually24), indicating the line on the screen where the top of thewindow will appear.

column is an integer or integer variable between one and the max-imum number of columns allowed by your terminal(usually 80), indicating the column of the screen wherethe left margin of the window will appear.

WITH is a required keyword to specify the vertical and horizon-tal dimensions of the window, in characters.

integer is an integer or integer variable.

ROWS is a keyword to specify the height of the window.

COLUMNS is a keyword to specify the width of the window.

FORM is an optional keyword.

form-file is the pathname of a compiled form specification file(excluding the .frm extension).

ATTRIBUTE is an optional keyword.

(attribute-list) is a list of one or more window display attributes.

7-160 INFORMIX-4GL Statement Syntax

Page 527: Manual Informix

OPEN WINDOW

Notes1. 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 entireprogram. It must begin with a letter. Up to 17 additional characters caninclude letters, numbers, and underscores ( _ ).

3. You can use the WITH integer ROWS, integer COLUMNS clause to specifyexplicit dimensions for the window.

Alternatively, you can include a WITH FORM clause, so that INFOR-MIX-4GL automatically opens a window sized to the screen layout ofform-file and displays the form. INFORMIX-4GL determines the width ofthe window from the rightmost character of the screen form and calcu-lates 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 OPTIONSstatement, the default value of this sum is form-length + 1, whereform-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 windowthat displays a single form. You cannot use a CLOSE FORM statement toclose a form that the WITH FORM clause displays, but CLOSE WINDOWcloses the form automatically.

If you want to display more than one form in a window or want a win-dow larger than the one that INFORMIX-4GL creates when it executes theWITH FORM clause, you must specify explicit window dimensions withthe WITH integer ROWS, integer COLUMNS clause. In that case, you mustalso open, display, and close the form(s) yourself.

5. When you OPEN a window, INFORMIX-4GL uses line-values specified inthe most recently executed OPTIONS statement for the Prompt, Message,Form, and Comment lines. Values are relative to the first or last line of thenewly opened window. To change the values for these reserved lines(without disabling the OPTIONS statement specifications for other win-dows), you can include an ATTRIBUTE clause.

6. An ATTRIBUTE clause in the OPEN WINDOW statement can include thefollowing attributes:

INFORMIX-4GL Statement Syntax 7-161

Page 528: Manual Informix

OPEN WINDOW

Attribute Default SettingBORDER No bordercolor (see note 13) The default foreground color on your terminalREVERSE No reverse videoPROMPT LINE line-value FIRST ( = 1 )MESSAGE LINE line-value FIRST + 1 ( = 2 )FORM LINE line-value FIRST + 2 ( = 3 )COMMENT LINE line-value LAST - 1 (for the screen)

LAST (for all other windows)

After the PROMPT, MESSAGE, and COMMENT keywords, line-value can bean integer, a program variable, FIRST plus an optional integer, or LASTminus 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 ormore of these reserved lines, INFORMIX-4GL increases its line-value toFIRST or decreases it to LAST, as appropriate.

8. If the window is not wide enough to display part of the text that you spec-ify with the PROMPT, MESSAGE, or DISPLAY statement (or with theCOMMENTS attribute of a screen form), INFORMIX-4GL generates a run-time error.

9. INFORMIX-4GL displays system error messages and text associated withthe ERROR statement in a borderless window on the Error line. INFOR-MIX-4GL opens the window as necessary and closes it at the nextkeystroke to erase the message.

Since the position of the Error line is relative to the screen, rather than tothe current window, the ATTRIBUTE clause of an OPEN WINDOW state-ment 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

Page 529: Manual Informix

OPEN WINDOW

11. When you use the BORDER attribute, INFORMIX-4GL draws a border out-side the window area that you specify. For example, if you open thefollowing window

OPEN WINDOW w1 AT 10,10 WITH 5 ROWS, 30 COLUMNSATTRIBUTE (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 termcapor terminfo files. You can specify alternative border characters in thesefiles. Otherwise, INFORMIX-4GL uses the hyphen ( - ) for horizontal lines,the vertical bar ( | ) for vertical lines, and the plus ( + ) sign for corners, asillustrated in the preceding example. See Appendix I,“Modifying termcap and terminfo,” and the manual that comes withyour terminal for information about making changes to your termcap orterminfo 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-4GLreserves 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 windowson these terminals: two columns to the left of the window, and two col-umns to the right.

13. Use any of the following keywords for color in an ATTRIBUTE clause tospecify the foreground of a window:

WHITE RED BLUE INVISIBLEYELLOW CYAN BLACK BOLDMAGENTA GREEN DIM NORMAL

14. If you specify a color in the ATTRIBUTE clause of an OPEN WINDOW state-ment, it becomes the default color for anything displayed in the windowexcept a menu. You can override the default color for a particular displayby specifying a different color in the ATTRIBUTE clause of a CONSTRUCT,

INFORMIX-4GL Statement Syntax 7-163

Page 530: Manual Informix

OPEN WINDOW

DISPLAY, DISPLAY ARRAY, DISPLAY FORM, INPUT, or INPUT ARRAYstatement.

15. Windows are stacked in the order that they are opened. See the CUR-RENT WINDOW and CLOSE WINDOW statements for informationabout how these statements affect the window stack.

ExamplesOPEN WINDOW w1 AT 5, 5

WITH FORM "custform"

OPEN WINDOW w2 AT 10, 12WITH 5 ROWS, 40 COLUMNSATTRIBUTE (BORDER, PROMPT LINE 3)

Related StatementsCLEAR WINDOW, CLOSE FORM, CLOSE WINDOW, CURRENT WINDOW,OPTIONS

7-164 INFORMIX-4GL Statement Syntax

Page 531: Manual Informix

OPTIONS

OPTIONS

OverviewThe OPTIONS statement can modify the reserved line positions and input ordisplay attributes for screen forms, and can change the keys for screen oper-ations and program aids (like help messages).

SyntaxOPTIONS {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 ) } [ , . . . ]

ExplanationOPTIONS is a required keyword.

line-value is an integer expression, indicating the line of the currentwindow or screen to display the reserved line specified bythe preceding keywords. The line-value can include the key-words FIRST or LAST.

MESSAGELINE

are optional keywords to position the Message line. Thedefault line-value is FIRST + 1 (that is, line 2 of the currentwindow).

PROMPTLINE

are optional keywords to position the Prompt line. Thedefault line-value is the FIRST window line.

COMMENTLINE

are optional keywords to position the Comment line. Thedefault line-value is LAST - 1 for the screen, and LAST for allother windows.

ERROR LINE are optional keywords to position the Error line. The defaultline-value is the LAST line of the screen.

INFORMIX-4GL Statement Syntax 7-165

Page 532: Manual Informix

OPTIONS

FORM LINE are optional keywords to position the first line of a form. Thedefault line-value is FIRST + 2 (that is, the form will begin online 3 of the current window).

INPUT WRAP are optional keywords indicating that the cursor wrapsaround the list of input fields during the execution of anINPUT or CONSTRUCT statement until the Accept key ispressed. The default is INPUT NO WRAP.

INPUTNO WRAP

are optional keywords indicating that the INPUT orCONSTRUCT statement terminates upon a RETURN after thelast field. This option is the default.

key-name designates or a function or CTRL key whose action is speci-fied by preceding keywords.

INSERT KEY are optional keywords to specify the key that opens up a linefor data insertion in INPUT ARRAY statements. If you do notspecify an Insert key, the default is [ F1 ].

DELETE KEY are optional keywords to specify the key that deletes a linein INPUT ARRAY statements. The default is [ F2 ].

NEXT KEY are optional keywords to specify the key that scrolls to thenext page in the INPUT ARRAY or DISPLAY ARRAY state-ment. The default is [ F3 ].

PREVIOUS KEY are optional keywords to specify the key that scrolls to theprevious page in the INPUT ARRAY or DISPLAY ARRAY state-ment. The default is [ F4 ].

ACCEPT KEY are optional keywords specifying the key to terminate theINPUT, INPUT ARRAY, DISPLAY ARRAY, and CONSTRUCTstatements. If you do not specify an Accept key, the defaultis the ESCAPE key.

HELP FILE are optional keywords to specify the file that contains pro-grammer-defined help messages. (Appendix E describesmkmessage, the help message utility.)

help-file is the pathname, enclosed in quotation ( " ) marks, of the filecontaining help messages.

HELP KEY are optional keywords to specify the key that displays helpmessages. The default is CTRL-W.

INPUTATTRIBUTE

are optional keywords to specify field attributes that are ineffect when data values are entered.

attribute-list is a list of one or more screen display attributes, or the key-words FORM or WINDOW.

7-166 INFORMIX-4GL Statement Syntax

Page 533: Manual Informix

OPTIONS

DISPLAYATTRIBUTE

are optional keywords to specify screen attributes that are ineffect when data values are displayed.

Notes1. 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 toseparate the items with commas.)

2. You can issue the OPTIONS statement more than once. The values set inthe 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 thefollowing formats:

integerFIRST [ + integer ]LAST [ - integer ]

Here FIRST is the first line of the current window (line 1), and LAST is thelast line of the current window.

4. The line-value for the Error line is relative to the screen, rather than to thecurrent window. The line-value of any other reserved line is relative to thefirst line of the current window (or to the screen, if that is the currentwindow).

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 letterexcept A, D, H, L, Q, R, S, or X . The key-name notation for isESCor 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 thesefor the Insert key, Delete key, Next key, Previous key, Accept key, or Helpkey. In addition, you might not be able to use some other keys, such asCTRL-C, CTRL-S, CTRL-Q, or CTRL-Z, depending on your implementationof the UNIX operating system.

7. During a CONSTRUCT, DISPLAY, DISPLAY ARRAY, DISPLAY FORM, INPUT,or INPUT ARRAY statement, INFORMIX-4GL checks for attributes andreserved line positions in the following order of precedence (from highestto 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

Page 534: Manual Informix

OPTIONS

3. Any default attributes in the syscolatt table of fields linked todatabase columns. (See the description of the “The upscol Utility” inAppendix E.)

4. Any attributes and reserved line positions specified in the most recentOPTIONS statement.

5. Any ATTRIBUTE clause for the current form in the most recentDISPLAY FORM statement.

6. Any ATTRIBUTE clause of the current window in the most recentOPEN WINDOW statement.

7. The default reserved line positions and the default foreground coloron your terminal.

8. The attribute-list supports the same keyword options as in the ATTRIBUTEclause of the DISPLAY statement, plus two additional options, FORM andWINDOW:

WHITE BLUE REVERSEYELLOW BLACK BLINKMAGENTA DIM UNDERLINERED INVISIBLE FORMCYAN BOLD WINDOWGREEN NORMAL

9. The INPUT ATTRIBUTE clause specifies the screen attributes to be usedduring a CONSTRUCT, INPUT, or INPUT ARRAY statement when noattribute-list is specified in those statements or in the specification file ofthe current form.

10. Similarly, the DISPLAY ATTRIBUTE clause specifies the screen attributes tobe used during a DISPLAY or DISPLAY ARRAY statement when noattribute-list is specified in those statements or in the specification file ofthe current form.

11. Include the FORM keyword with a DISPLAY ATTRIBUTE or INPUTATTRIBUTE statement to instruct INFORMIX-4GL to use the displayattributes of the current form. Use the WINDOW keyword of the samestatements to instruct INFORMIX-4GL to use the display attributes of thecurrent window.

7-168 INFORMIX-4GL Statement Syntax

Page 535: Manual Informix

OPTIONS

ExamplesThe following statement sets three reserved line positions and specifies theNext 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 valuesare input, regardless of the foreground form color or window color:

OPTIONS INPUT ATTRIBUTE (green)

Related StatementsCONSTRUCT, DISPLAY, DISPLAY ARRAY, DISPLAY FORM, ERROR, INPUT,INPUT ARRAY, MENU, MESSAGE, OPEN FORM, OPEN WINDOW, PROMPT

INFORMIX-4GL Statement Syntax 7-169

Page 536: Manual Informix

OUTPUT TO REPORT

OUTPUT TO REPORT

OverviewUse the OUTPUT TO REPORT statement to pass a single row of data to a report.

SyntaxOUTPUT TO REPORT report-name (expr-list)

ExplanationOUTPUT TOREPORT

are required keywords.

report-name is the identifier of a report.

expr-list is a list of one or more expressions, separated by commas.

Notes1. 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 andtype of arguments in the REPORT routine.

ExampleOUTPUT TO REPORT rept1 (v_pers.*)

Related StatementsFINISH REPORT, REPORT, START REPORT

7-170 INFORMIX-4GL Statement Syntax

Page 537: Manual Informix

PREPARE

PREPARE

OverviewUse the PREPARE statement to preprocess an SQL statement for later execu-tion. The SQL statements are listed in Chapter 3.

SyntaxPREPARE statement-id FROM string-spec

Explanation:PREPARE is a required keyword.

statement-id is an SQL identifier for a statement.

FROM is a required keyword.

string-spec is either a string constant enclosed in quotation marks or aCHAR type program variable. The string-spec must containan SQL statement.

Notes1. The statement(s) described in string-spec cannot contain program vari-

ables. Use a question mark ( ? ) as a placeholder for an input value thatwill be supplied in an EXECUTE, OPEN, or PUT statement. Do not use aquestion mark as a placeholder for an SQL identifier such as a databasename, 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 UPDATEclause.

3. The string-spec cannot include any of the following statements: CLOSE,DECLARE, EXECUTE, FETCH, LOAD, OPEN, PREPARE, UNLOAD, andWHENEVER.

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 canrefer 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

Page 538: Manual Informix

PREPARE

6. INFORMIX-4GL can execute several SQL statements as one action if youpreprocess 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 eachSQL statement. You must also terminate each string (except the last) witha semicolon ( ; ) symbol before the right-hand quotation ( " ) mark. For anexample, see the section “Preparing Multiple SQL Statements” inChapter 3. (The statements cannot include SELECT, DATABASE, CLOSEDATABASE, CREATE DATABASE, or DROP DATABASE.)

7. Within a module, statement-id can apply to only one SQL statement orsequence of statements. Do not specify the same statement-name inanother PREPARE statement in the same module.

8. You can use a subsequent FREE statement to release the database engineresources that have been allocated to statement-id.

ExampleLET select_2 = "select * from orders ",

"where customer_nu m = ? and ", "order_date > ?"PREPARE query_2 FROM select_2

Related StatementsDECLARE, EXECUTE, FOREACH, FREE, OPEN

7-172 INFORMIX-4GL Statement Syntax

Page 539: Manual Informix

PROMPT

PROMPT

OverviewUse the PROMPT statement to prompt the user for keyboard input, and toaccept a value entered by the user.

SyntaxPROMPT display-list [ ATTRIBUTE ( attribute-list) ]

FOR [ CHAR ] variable[ HELP help-number ][ ATTRIBUTE ( attribute-list) ][ ON KEY ( key-list)

statement. . .

. . .END PROMPT ]

ExplanationPROMPT is a required keyword.

display-list is a list of one or more program variables or string constants,separated by commas.

ATTRIBUTE is a keyword to specify screen display attributes.

(attribute-list) is a list (in parentheses) of one or more screen displayattributes, separated by commas.

FOR is a required keyword.

CHAR is an optional keyword.

variable is the program variable that will contain the value typed inby the user.

HELP is an optional keyword.

help-number is an integer that identifies the help message for this PROMPTstatement in the help file designated in the OPTIONSstatement.

ON KEY are optional keywords.

key-list is a list of one or more function or CTRL key designations. Itcan also include ESCAPE (if you have specified another keyas the Accept key in the OPTIONS statement) or INTERRUPT(if you have executed a DEFER INTERRUPT statement).

INFORMIX-4GL Statement Syntax 7-173

Page 540: Manual Informix

PROMPT

statement is an INFORMIX-4GL statement.

ENDPROMPT

are keywords to terminate a PROMPT statement (requiredonly if an ON KEY clause is used).

Notes1. INFORMIX-4GL displays the string generated by replacing the variables

in display-list with their current values on the Prompt line if an open formis displayed. The prompt occurs at the current cursor position if no formis 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 characterinput without requiring a carriage return.

4. If INFORMIX-4GL cannot convert the value entered by the user to the datatype of variable, it returns a negative error code in the global variablestatus 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 theOPTIONS statement).

• Interrupt, if you have executed a DEFER INTERRUPT statement. (Whenthe user presses the Interrupt key under these conditions, INFOR-MIX-4GL executes the statements in the ON KEY clause and setsint_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 CTRLkeys are reserved for editing functions in the CONSTRUCT, INPUT, andINPUT ARRAY statements.

• Other keys like CTRL-S that may have special meaning on your imple-mentation of UNIX.

6. INFORMIX-4GL terminates PROMPT and passes control to the statementsfollowing an ON KEY clause when the user presses a key specified in key-

7-174 INFORMIX-4GL Statement Syntax

Page 541: Manual Informix

PROMPT

list. In this case, the value in variable is undetermined. After completingthe ON KEY clause, INFORMIX-4GL passes control to the statements fol-lowing END PROMPT.

7. The notation for function keys is F1 through F36 . The notation for CON-TROL 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 Interruptkey (often CTRL-C or DEL) is INTERRUPT.

8. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within theON KEY clause of a PROMPT statement. However, you can call a functionthat executes one of these statements. If you include an ON KEY clause,any HELP or ATTRIBUTE specifications must appear before the ON KEYclause, not after it.

9. The first ATTRIBUTE clause applies to the display-list, while the second isin effect during input.

10. The HELP clause and the second ATTRIBUTE clause can appear in anyorder.

11. Neither ATTRIBUTE clause can be in effect when the terminal is in linemode. The terminal is in line mode until the first time that a screen-I/Ostatement is executed. It returns to line mode when you issue anyDISPLAY statement that has no BY NAME, TO, or AT clause.

12. The attribute-list temporarily overrides any attributes specified in anOPTIONS or OPEN WINDOW statement.

13. These keywords can appear in the ATTRIBUTE clause:

WHITE = NORMAL REVERSEYELLOW = BOLD BLINKMAGENTA = BOLD UNDERLINERED = BOLDCYAN = DIMGREEN = DIMBLUE = DIMBLACK = INVISIBLE

You can specify zero or one of the keywords in the left-hand columns, andfrom zero to three from the right-hand column (but some terminals maynot support some combinations). On color terminals, NORMAL is inter-preted 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 onmonochrome terminals of keywords that specify color.

These keywords cannot produce the effects suggested by their namesunless the termcap or terminfo files and the physical terminals supportthe attribute. (See Appendix I, “Modifying termcap and terminfo.”)

INFORMIX-4GL Statement Syntax 7-175

Page 542: Manual Informix

PROMPT

Note: Some terminal entries in termcap or terminfo include the sg#1 orxmc#1 capabilities. On these terminals, the first character of display-list isreplaced 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 youspecify any display attributes.

14. On UNIX systems that use terminfo files rather than termcap, INFOR-MIX-4GL does not support attributes that specify colors, and the onlyvalid attribute-list keywords are REVERSE and UNDERLINE.

ExamplePROMPT "Enter the Customer Number: "

FOR v.cust_noON KEY (CONTROL-E)

GOTO stop_now:END PROMPT

Related StatementsDISPLAY, DISPLAY ARRAY, INPUT, INPUT ARRAY, OPTIONS

7-176 INFORMIX-4GL Statement Syntax

Page 543: Manual Informix

PUT

PUT

OverviewUse the PUT statement to store a row in the INSERT buffer for later insertioninto the database table.

SyntaxPUT cursor-name

[ FROM variable-list ]

ExplanationPUT is a required keyword.

cursor-name is the name of a cursor that has been DECLAREd for anINSERT statement.

FROM is an optional keyword.

variable-list is a list of program variables, separated by commas, corre-sponding to the ‘‘?’’ parameters in the PREPAREd INSERTstatement associated with cursor-name.

Notes1. 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 cursoris referred to as an INSERT cursor.

2. The PUT statement puts a row in the buffer created when cursor-name wasOPENed. When you flush the buffer (by executing a series of PUT state-ments, a CLOSE statement, or a FLUSH statement), INFORMIX-4GL insertsthe buffered rows into the database table as a block.

3. INFORMIX-4GL does not create an INSERT buffer for a cursor associatedwith an INSERT statement that contains only constants in the VALUESclause. If you execute a PUT statement for such a cursor, INFORMIX-4GLincrements a counter that keeps track of the number of rows to be insertedinto the database. The database is updated only when you issue a FLUSHor CLOSE statement.

4. You close a cursor by issuing a CLOSE statement. Exiting a program with-out closing an insert cursor leaves the buffer unflushed. Rows inserted

INFORMIX-4GL Statement Syntax 7-177

Page 544: Manual Informix

PUT

into the buffer since the last flush are lost. You cannot rely on the end ofprogram to close the cursor and flush the buffer.

5. The global variables status (whose value is received from SQLCA.SQL-CODE) and SQLCA.SQLERRD[3] indicate the result of each PUT statement.

If INFORMIX-4GL simply puts a row in the INSERT buffer, it sets statusand SQLCA.SQLERRD[3] to zero. If, as the result of a PUT statement,INFORMIX-4GL successfully inserts a block of rows into the database, itsets status to zero and sets SQLCA.SQLERRD[3] to the number of rowsinserted. If, as the result of a PUT statement, INFORMIX-4GL is unsuccess-ful in its attempt to insert an entire block of rows into the database, it setsstatus to a negative number (specifically, the number of the error mes-sage) and sets SQLCA.SQLERRD[3] to the number of rows successfullyinserted into the database.

6. Whenever the buffer is flushed, SQLCA.SQLERRD[3] is set to the numberof rows successfully inserted into the database. If an error occurs duringthe flushing of a buffer, the buffered rows that follow the last successfullyinserted row are discarded.

7. If your database has transactions, you must issue the PUT statementwithin a transaction.

8. If cursor-name has been DECLAREd for a PREPAREd INSERT statement thatincludes ‘‘?’’ parameters, you must use the PUT statement with a FROMclause. After the FROM keyword, you can list the variable(s) containingthe value(s) that INFORMIX-4GL substitutes for the ‘‘?’’ parameters in thePREPAREd INSERT statement.

ExamplesDECLARE icurs CURSOR FOR

INSERT INTO manufact VALUES (m_code, m_name)OPEN icursPUT icurs

PREPARE ins_stmt FROM"INSERT INTO manufact VALUES (?, ?)"

DECLARE ins_curs CURSOR FOR ins_stmtOPEN ins_cursPUT ins_curs FROM m_code, m_name

Related StatementsCLOSE, DECLARE, FLUSH, OPEN, PREPARE

7-178 INFORMIX-4GL Statement Syntax

Page 545: Manual Informix

RECOVER TABLE

RECOVER TABLE

OverviewIn the event of a system failure, use the RECOVER TABLE statement to restorea database table from a backup copy and an audit trail file.

SyntaxRECOVER TABLE table-name

ExplanationRECOVER TABLE are required keywords.

table-name is the name of the table you want to recover.

Notes1. Once you have recovered the table, use the DROP AUDIT statement to

remove the contents of the audit trail file. Run the CREATE AUDIT state-ment 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 consistentrecord numbers for rows where changes have taken place. If RECOVERTABLE finds inconsistencies, it stops restoring the table.

3. You must own table-name or have DBA status to use the RECOVER TABLEstatement.

ExampleThe 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

Page 546: Manual Informix

RECOVER TABLE

Related StatementsCREATE AUDIT, DROP AUDIT

7-180 INFORMIX-4GL Statement Syntax

Page 547: Manual Informix

RENAME COLUMN

RENAME COLUMN

OverviewUse the RENAME COLUMN statement to change the name of a column.

SyntaxRENAME COLUMN table.oldcolumn TO newcolumn

ExplanationRENAME COLUMN are required keywords.

table is the required name of the table containing the columnwhose name is to be changed.

oldcolumn is the name of the column to be renamed.

TO is a required keyword.

newcolumn is the new name to be assigned to the column. Thenewcolumn must satisfy the requirements for an SQLidentifier, and cannot duplicate another column name inthe table.

Notes1. 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.

ExampleRENAME COLUMN customer.customer_num TO c_num

Related StatementsALTER TABLE, CREATE TABLE, INSERT, DROP TABLE, RENAME TABLE

INFORMIX-4GL Statement Syntax 7-181

Page 548: Manual Informix

RENAME TABLE

RENAME TABLE

OverviewUse the RENAME TABLE statement to change the name of a table in thesystem catalogs.

SyntaxRENAME TABLE oldname TO newname

ExplanationRENAME TABLE are required keywords.

oldname is the current name of the table to be renamed.

TO is a required keyword.

newname is the new name that you want to assign to the table.

Notes1. In a non-MODE ANSI database, the newname identifier must be unique

among tables and synonyms. In a MODE ANSI database, it must be uniqueamong tables and synonyms that you own.

2. You can RENAME a table only when you own the table, have DBA privi-lege, or have been granted ALTER permission on the table.

3. You can specify owner.oldname in a RENAME TABLE statement, but a com-pile-time error results if you specify owner.newname.

4. The RENAME TABLE statement cannot be rolled back.

7-182 INFORMIX-4GL Statement Syntax

Page 549: Manual Informix

RENAME TABLE

ExampleThis example moves the quantity column to the third place:

CREATE TABLE newtab(item_num SMALLINT,

order_num INTEGER,quantity SMALLINT,stock_num SMALLINT,manu_code CHAR(4),total_price MONEY(8)

)

INSERT INTO newtabSELECT item_num, order_num,

quantity, stock_num, manu_code,total_price FROM items

DROP TABLE items

RENAME TABLE newtab TO items

Related StatementsALTER TABLE, CREATE TABLE, INSERT, DROP TABLE, RENAME COLUMN

INFORMIX-4GL Statement Syntax 7-183

Page 550: Manual Informix

REPORT

REPORT

OverviewUse the REPORT routine to provide the format specifications for a report.

SyntaxREPORT report-name ( variable-list )

[ DEFINE-statement ]. . .

[ OUTPUToutput-statement. . . ]

[ ORDER [ EXTERNAL ] BY sort-list ]FORMAT

format-statement. . .4gl-statement. . .

END REPORT

ExplanationREPORT 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 vari-

ables 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

Page 551: Manual Informix

REPORT

Notes1. 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 invariable-list.

2. See Chapter 5 for a discussion of the OUTPUT, ORDER BY, and FORMATsections of the REPORT routine.

3. If INFORMIX-4GL statements occur in the control blocks of the FORMATsection, they are executed during the report-printing phase. If the data issorted outside the report, report printing takes place with each OUTPUTTO REPORT statement. This is called a one-pass report. If the data is sortedinside the report, report printing takes place with the FINISH REPORTstatement. This is called a two-pass report.

If 4GL statements occur in the OUTPUT TO REPORT loop as well as in thereport, INFORMIX-4GL alternately executes the 4GL statements in theOUTPUT TO REPORT loop and the 4GL statements in the report during aone-pass report. In contrast, INFORMIX-4GL repeatedly executes all the4GL statements in the OUTPUT TO REPORT loop before executing the 4GLstatements in the report during a two-pass report.

ExampleThe simplest report displays the output of a query:

DECLARE simp_curs CURSOR FORSELECT * FROM CUSTOMER

START REPORT simpleFOREACH simp_curs INTO cust.*

OUTPUT TO REPORT simple(cust.*)END FOREACHFINISH REPORT simple...

REPORT simple (x)DEFINE x RECORD LIKE customer.*FORMAT

EVERY ROWEND REPORT

Related StatementsFINISH REPORT, OUTPUT TO REPORT, START REPORT

INFORMIX-4GL Statement Syntax 7-185

Page 552: Manual Informix

RETURN

RETURN

OverviewUse the RETURN statement to leave a FUNCTION routine and to return valuesto the calling routine.

SyntaxRETURN [expr-list]

ExplanationRETURN is a required keyword.

expr-list is an optional list of one or more expressions, separated bycommas.

Notes1. The RETURN statement can occur only within a FUNCTION routine and

directs INFORMIX-4GL to exit the function and to return to the callingroutine (MAIN, FUNCTION, or REPORT).

2. The expressions in expr-list must match in number and type the argumentlist in the RETURNING clause of the CALL statement.

Related StatementFUNCTION

7-186 INFORMIX-4GL Statement Syntax

Page 553: Manual Informix

REVOKE

REVOKE

OverviewUse the REVOKE statement to remove another user’s access privileges for adatabase or table.

SyntaxREVOKE { tab-privilege ON table-name | db-privilege }

FROM { PUBLIC | user-list}

ExplanationREVOKE is a required keyword.

tab-privilege is one or more of the following table-level access privileges,separated by commas:ALTER Adds or deletes columns or modifies

data types of columnsDELETE Deletes rowsINDEX Creates indexesINSERT Inserts rowsSELECT Retrieves dataUPDATE Changes column valuesALL [PRIVILEGES] All of the above

ON is a required keyword.

table-name is the name of the table for which you are revoking accessprivileges.

db-privilege is one of the following database-level access types:CONNECT allows access to database tables without

permission to create permanent tablesand indexes.

RESOURCE allows access to database tables withpermission to create permanent tablesand indexes.

DBA allows full database administratorprivileges.

FROM is a required keyword.

INFORMIX-4GL Statement Syntax 7-187

Page 554: Manual Informix

REVOKE

PUBLIC is the keyword to revoke access privilege from all users.

user-list is a list of login names for the users whose access privilegeyou are revoking. You can enter one login name or a series oflogin names, separated by commas.

Notes1. You cannot roll back the REVOKE statement.

2. You can revoke database-level access privileges only if you have DBAstatus.

3. You can revoke only those table-level access privileges that you havegranted to another user.

4. You cannot revoke privileges from yourself.

5. Although you can grant UPDATE and SELECT privileges for specific col-umns, you cannot revoke these privileges column by column. If yourevoke UPDATE or SELECT privileges from a user, INFORMIX-4GL auto-matically revokes all UPDATE and SELECT privileges that you have evergranted to that user for table-name. You can then re-grant privileges forspecific columns.

6. Only a DBA recipient can revoke the DBA privilege from another recipi-ent. If the database creator grants DBA privileges to another user, thatperson 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 privi-leges from users with DBA or RESOURCE status, you must revokeCONNECT as well as DBA or RESOURCE.

ExamplesREVOKE ALL ON orders FROM PUBLIC

REVOKE DELETE, UPDATEON customer FROM jeff, judy

REVOKE CONNECT FROM enid, felix

Related StatementGRANT

7-188 INFORMIX-4GL Statement Syntax

Page 555: Manual Informix

ROLLBACK WORK

ROLLBACK WORK

OverviewUse the ROLLBACK WORK statement to undo all modifications made to thedatabase during the current transaction.

SyntaxROLLBACK WORK

ExplanationROLLBACK WORK are required keywords.

Note1. If you use the ROLLBACK WORK statement in a routine that is called by a

WHENEVER statement, be sure to specify WHENEVER ERROR CONTINUEand WHENEVER WARNING CONTINUE before the ROLLBACK WORKstatement. This will prevent the program from looping if the ROLLBACKWORK statement fails with an error or warning.

2. See the “Transactions” section in Chapter 3 for more information abouttransactions 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 thoseDECLAREd WITH HOLD, although using it for this purpose is notrecommended.

Related StatementsBEGIN WORK, COMMIT WORK

INFORMIX-4GL Statement Syntax 7-189

Page 556: Manual Informix

ROLLFORWARD DATABASE

ROLLFORWARD DATABASE

OverviewUse the ROLLFORWARD DATABASE statement to cause INFORMIX-4GL toapply the transactions registered in the transaction log file to a backup copyof your database, recovering all completed transactions.

SyntaxROLLFORWARD DATABASE database-name

ExplanationROLLFORWARDDATABASE

are required keywords.

database-name is the name of a database.

Notes1. Immediately after you roll forward a database, it is in EXCLUSIVE mode,

with no transactions. After the database is closed and reopened, itbecomes accessible to other users, and transactions can resume.

2. See the section “Transactions” in Chapter 3 for more information.

Related StatementsBEGIN WORK, COMMIT WORK, START DATABASE, ROLLBACK WORK

7-190 INFORMIX-4GL Statement Syntax

Page 557: Manual Informix

RUN

RUN

OverviewUse the RUN statement to execute a system program.

SyntaxRUN command-line [ RETURNING integer-variable

| WITHOUT WAITING ]

ExplanationRUN 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 char-acter 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 theRUN statement.

WITHOUT WAITING are optional keywords.

NoteRUN spawns a child process described by command-line. The WITHOUTWAITING option instructs INFORMIX-4GL to continue immediately to thenext 4GL statement, while the RETURNING option instructs INFORMIX-4GLto await the return value before continuing to the next 4GL statement. If nei-ther optional clause is present, INFORMIX-4GL waits until the child processis completed (and ignores the return code) before continuing to the next 4GLstatement.

ExamplesRUN "date_script" RETURNING error_val

RUN "isql -qr myscript"

RUN charval[i]

INFORMIX-4GL Statement Syntax 7-191

Page 558: Manual Informix

SCROLL

7

SCROLL

OverviewUse the SCROLL statement to move rows of a screen record through a screenarray.

SyntaxSCROLL { field-list | screen-record. * } [ , . . . ]

{ UP | DOWN } [ BY integer ]

ExplanationSCROLL is a required keyword.

field-list is a list of one or more screen field names, separated bycommas.

screen-record is the name of a screen record.

UP is an optional keyword indicating that the data on the screenshould move upwards.

DOWN is an optional keyword indicating that the data on the screenshould move downwards.

BY is an optional keyword.

integer is an INTEGER constant or variable.

Notes1. 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 lefton the screen.

ExampleSCROLL sc_item UP BY 2

Related StatementsDISPLAY ARRAY, INPUT ARRAY

-192 INFORMIX-4GL Statement Syntax

Page 559: Manual Informix

SELECT

SELECT

OverviewUse the SELECT statement to query the current database.

The SELECT statement can include up to eight clauses. Only the SELECTclause and the FROM clause are required.

SyntaxSELECT 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 detaileddescriptions of these clauses.

INFORMIX-4GL Statement Syntax 7-193

Page 560: Manual Informix

SET EXPLAIN

SET EXPLAIN

OverviewUse the SET EXPLAIN statement to record how the query processor is access-ing the database when executing a query.

SyntaxSET EXPLAIN { ON | OFF }

ExplanationSET EXPLAIN are required keywords.

ON is a keyword to enable the EXPLAIN facility.

OFF is a keyword to disable the EXPLAIN facility. OFF is thedefault.

Notes1. When you issue SET EXPLAIN ON, the access procedures of all subsequent

queries are stored in the file sqexplain.out in your current directory. Ifsqexplain.out already exists, subsequent output is appended to it. SETEXPLAIN ON remains in effect until you issue SET EXPLAIN OFF, or theprogram ends.

2. SET EXPLAIN estimates the cost in CPU resources (a weighted sum of diskaccesses and total rows processed), indicates the order of table access, andestimates the number of rows returned. For each table, SET EXPLAIN iden-tifies the type of access and the column(s) that serves as a filter, includingwhether the filtering is through an index. The following table-accesstypes are available:

SEQUENTIAL SCAN reads rows in sequence.

INDEX PATH scans one or more indexes.

AUTOINDEX PATH creates a temporary index.

3. The name of the owner precedes each table name in the output file.

7-194 INFORMIX-4GL Statement Syntax

Page 561: Manual Informix

SET EXPLAIN

ExamplesThe following example shows an sqexplain.out output file for a simple queryand for a complex query from one table.

QUERY:------select fname, lname, company from customer;

Estimated Cost: 4Estimated # of Rows Returned: 18

1) joe.customer: SEQUENTIAL SCAN

QUERY:------select fname, lname, company from customerwhere company matches "Sport*"

and customer_num between 110 and 115order by lname;

Estimated Cost: 3Estimated # of Rows Returned: 1Temporary Files Required For: Order By

1) joe.customer: INDEX PATH

Filters: joe.customer.company MATCHES "Sport*"

(1) Index Keys: customer_numLower Index Filter:

joe.customer.customer_num >= 110Upper Index Filter:

joe.customer.customer_num <= 115

INFORMIX-4GL Statement Syntax 7-195

Page 562: Manual Informix

SET EXPLAIN

The next example is from an sqexplain.out output file for a multiple-tablequery.

QUERY:------select * from customer, orders, items wherecustomer.customer_num = orders.customer_num andorders.order_num = items.order_num;

Estimated Cost: 110Estimated # of Rows Returned: 41

1) joe.orders: SEQUENTIAL SCAN

2) joe.customer: INDEX PATH

(1) Index Keys: customer_numLower Index Filter: joe.customer.customer_num

= joe.orders.customer_num

3) joe.items: INDEX PATH

(1) Index Keys: order_numLower Index Filter: joe.items.order_num

= joe.orders.order_num

Related StatementsALTER INDEX, CREATE INDEX, SELECT, UPDATE STATISTICS

Note: Additional statistics are available for query processing when you useINFORMIX-OnLine as the database engine. As a result, estimates for the cost andthe number of rows returned may be more precise under INFORMIX-OnLine.

7-196 INFORMIX-4GL Statement Syntax

Page 563: Manual Informix

SET LOCK MODE ( O )

SET LOCK MODE ( O )

OverviewUse the SET LOCK MODE statement to determine whether subsequent INFOR-MIX-4GL calls wait for a locked row to become unlocked.

SyntaxSET LOCK MODE TO [ NOT ] WAIT

ExplanationSET LOCK MODE are required keywords.

TO is a required keyword.

NOT is an optional keyword.

WAIT is a required keyword.

Notes1. 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 FORUPDATE) 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 previouslyexecuted SET LOCK MODE TO WAIT and want to return to the defaultstate.

2. The TO WAIT option causes INFORMIX-4GL to wait on an attempt to alteror delete a row (or to SELECT a row FOR UPDATE) that another process haslocked until the locked row becomes unlocked.

3. Use the SET LOCK MODE TO WAIT statement with extreme caution. If thelocking process fails and does not remove the lock, your statement couldwait indefinitely.

4. This feature is available only on systems that have record-level lockingand applies only to row-level locking. Any attempt by another user toaccess 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 supportkernel locking. An error is generated if you use the SET LOCK MODE state-ment with a system that does not support kernel locking.

INFORMIX-4GL Statement Syntax 7-197

Page 564: Manual Informix

SET LOCK MODE ( O )

Related StatementLOCK TABLE

7-198 INFORMIX-4GL Statement Syntax

Page 565: Manual Informix

SLEEP

SLEEP

OverviewUse the SLEEP statement to cause the program to suspend operation for aperiod of time.

SyntaxSLEEP integer-expr

ExplanationSLEEP is a required keyword.

integer-expr is an expression that evaluates to INTEGER type.

NoteThe SLEEP statement causes the program to suspend operation for integer-expr seconds.

ExampleSLEEP 4

INFORMIX-4GL Statement Syntax 7-199

Page 566: Manual Informix

START DATABASE

START DATABASE

OverviewUse the START DATABASE statement to start a new transaction log file.

SyntaxSTART DATABASE database-name WITH LOG IN "pathname" [ MODE ANSI ]

ExplanationSTART DATABASE are required keywords.

database-name is the name of a database.

WITH LOG IN are required keywords.

pathname is the full pathname, enclosed in quotation ( " ) marks,of the transaction log file.

MODE ANSI are optional keywords to convert the database toMODE ANSI.

Notes1. 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 withouttransactions.

• 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 DATABASEstatement.

3. After a database is started as MODE ANSI, you receive an error if you donot use the owner.object naming convention to refer to an object owned byanother user. You must modify existing queries that reference a table,view, or synonym owned by another user to include the owner prefix. Seethe section “Owner Naming” in Chapter 3 of this manual.

4. Do not use the BEGIN WORK statement in programs that access a MODEANSI database. Since transactions are implicit in MODE ANSI, the BEGINWORK statement is not needed.

7-200 INFORMIX-4GL Statement Syntax

Page 567: Manual Informix

START DATABASE

5. Singleton transactions do not exist in MODE ANSI. For a singleton state-ment, you must issue a COMMIT WORK statement to commit atransaction, or a ROLLBACK WORK statement to roll the database back tothe last COMMIT WORK or ROLLBACK WORK statement.

6. See the section “Transactions” in Chapter 3 for more information onSTART DATABASE. See also the discussion of CREATE DATABASE earlierin this chapter for more information on MODE ANSI databases.

7. You can determine the type of database that a user selects by checking thereturn code from a DATABASE statement in the SQLCA.SQLAWARN char-acter string. See the section “SQLCA Record” in Chapter 3 for moreinformation.

8. You cannot remove MODE ANSI from a database. Once started as such, adatabase remains MODE ANSI.

ExampleSTART DATABASE stores

WITH LOG IN "/u/myname/stores.log" MODE ANSI

Related StatementsBEGIN WORK, COMMIT WORK, CREATE DATABASE, ROLLBACK WORK,ROLLFORWARD DATABASE

INFORMIX-4GL Statement Syntax 7-201

Page 568: Manual Informix

START REPORT

START REPORT

OverviewUse the START REPORT statement to begin processing a report.

SyntaxSTART REPORT report-name

[ TO { filename | PRINTER | PIPE program } ]

ExplanationSTART REPORT are required keywords.

report-name is the identifier of a report.

TO is an optional keyword.

filename is either a CHAR type variable or a quoted string constantcontaining the name of a system file.

PRINTER is an optional keyword.

PIPE is an optional keyword.

program is either a CHAR variable or a string constant containing thecommand line for a system program.

Notes1. Usually, you will execute the START REPORT statement just before a loop

in which you process the report data using the OUTPUT TO REPORTstatement.

2. If you use the TO clause, INFORMIX-4GL ignores any REPORT TO state-ment 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 out-put to your printer. The default printer command is lp or lpr; be sure tocheck with your system administrator. You can change the default by set-ting the DBPRINT environment variable. (See Appendix C.)

5. Use the TO PIPE option to pipe report output to program.

Related StatementsFINISH REPORT, OUTPUT TO REPORT, REPORT

7-202 INFORMIX-4GL Statement Syntax

Page 569: Manual Informix

UNLOAD

UNLOAD

OverviewUse the UNLOAD statement to write the data from a table to an ASCII file.

SyntaxUNLOAD TO "pathname" [ DELIMITER "char" ] SELECT-statement

ExplanationUNLOAD TO are required keywords.

pathname is a quoted string or a character variable that evaluates tothe pathname of the file in which to store the databasetable.

DELIMITER is an optional keyword to indicate that the following charseparates data fields in the file.

char is a single character that serves as the delimiter betweenfields. The char must appear in quotation marks.

SELECT-statement is a SELECT statement that retrieves the data to be writtento a file.

Notes1. 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 char-acter included in the DELIMITER clause, if one is provided. If noDELIMITER clause appears in the statement, INFORMIX-4GL checks thesetting in the DBDELIMITER environment variable, if it exists. The defaultdelimiter is the vertical bar ( | = ASCII 124).

If character data contains a delimiter character, INFORMIX-4GL automat-ically escapes it with a backslash to prevent interpretation as a specialcharacter. (Backslashes are automatically stripped when the field isLOADed.)

2. As in a DECLARE statement for a SELECT cursor, the SELECT-statement canbe either an unquoted SELECT statement, or the name of a string variablethat contains a SELECT statement.

3. NULL columns have no characters between delimiters.

INFORMIX-4GL Statement Syntax 7-203

Page 570: Manual Informix

UNLOAD

4. Trailing blanks in CHARACTER data are clipped. Number data types haveno leading blanks.

5. An INTEGER or SMALLINT zero is represented as 0 ; FLOAT, SMALL-FLOAT, 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, showingonly their field digits and delimiters. No type specification or qualifiersare output. INFORMIX-4GL uses the following pattern: yyyy-mm-ddhh: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 theSELECT statement to use the UNLOAD statement.

10. You cannot PREPARE an UNLOAD statement.

11. When you execute an UNLOAD statement, INFORMIX-4GL sets status tozero to indicate success, or to an error number to indicate failure. If anerror occurs, the SQLCODE and SQLERRD[2] error codes are set, asdescribed in Chapter 3. In any case, the value of SQLERRD[3] is set to thenumber of rows that UNLOAD copied to the file.

ExampleUNLOAD TO "cust.out" DELIMITER ";"

SELECT fname, lname, company, cityFROM customer

Related StatementsLOAD, SELECT

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

7-204 INFORMIX-4GL Statement Syntax

Page 571: Manual Informix

UNLOCK TABLE

UNLOCK TABLE

OverviewUse the UNLOCK TABLE statement to unlock a table that you previouslylocked with the LOCK TABLE statement.

SyntaxUNLOCK TABLE table-name

ExplanationUNLOCK TABLE are required keywords.

table-name is the name of the table you want to unlock.

NoteIf the database has transactions, the UNLOCK TABLE statement can not beused and generates an error. All locks placed on the table are released whenthe COMMIT WORK or ROLLBACK WORK statement is processed.

Related StatementLOCK TABLE

INFORMIX-4GL Statement Syntax 7-205

Page 572: Manual Informix

UPDATE

UPDATE

OverviewUse the UPDATE statement to change the values in one or more columns ofone or more rows in a table.

SyntaxUPDATE table-name SET { column-name = expr [ , . . . ] |

{ ( column-list ) | [ table-name. ] * } = { ( expr-list) | record-name.* } }[ WHERE { condition | CURRENT OF cursor-name } ]

ExplanationUPDATE is a required keyword.

table-name is the name of the table that contains the row(s) that youwant to update.

SET is a required keyword.

column-name is the name of a column you want to update.

expr is any combination of column names, constants, programvariables, arithmetic operators, or an SQL subquery thatreturns a single row of one value.

column-list is a list of the names of columns to be updated.

* refers to all columns in table-name. (You can substitutetable-name.* if you prefer.)

expr-list is a list of expressions that represent values corresponding tothe columns in column-list or the columns represented by theasterisk notation. In expr-list, you can specify multiple valuesusing a record name with the asterisk ( * ) or THRU notation.The list can also include an SQL subquery that returns a sin-gle row of multiple values.

record-name is the name of a program variable of type RECORD.

WHERE is an optional keyword.

condition is a condition for a standard WHERE clause made up of asearch condition that compares the values in one column tothe values in another column, to a program variable, or to aconstant. (For further information, refer to the explanation of

7-206 INFORMIX-4GL Statement Syntax

Page 573: Manual Informix

UPDATE

WHERE clauses in the section “The SELECT Statement” atthe end of this chapter.)

CURRENT OF are keywords.

cursor-name is the SQL identifier of a previously DECLAREd cursor.

Notes1. The expr can be a SELECT statement in parentheses that adheres to stan-

dard rules for subqueries. The SELECT statement can return no more thanone 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 thenumber of values produced in the expr-list.

4. Although the value returned by expr does not have to be of the same datatype as column-name, it must be compatible. You can put only CHAR datainto CHAR columns, and only numeric or character representations ofnumeric data into number columns.

5. If you use the CURRENT OF option in the WHERE clause, INFORMIX-4GLupdates the current row of the active set and leaves the cursor on thesame row.

6. If you do not specify any columns in the FOR UPDATE clause of aDECLARE statement, you can update any column in a subsequentUPDATE WHERE CURRENT OF statement. If you do specify one or morecolumns in the FOR UPDATE clause, you can update only those columnsin a subsequent UPDATE WHERE CURRENT OF statement. When youspecify the column names in the FOR UPDATE clause, INFORMIX-4GL canusually 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 executethe following form of the UPDATE statement:

UPDATE table-nameSET [ table-name .]* = record-name .*

When INFORMIX-4GL executes this form of the UPDATE statement, itautomatically skips any SERIAL column and the corresponding value inthe 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 ROLL-BACK WORK statements.

INFORMIX-4GL Statement Syntax 7-207

Page 574: Manual Informix

UPDATE

9. Each row affected by an UPDATE statement within a transaction is lockedfor the duration of the transaction; therefore, a single UPDATE statementthat affects a large number of rows locks those rows until the entire oper-ation is completed. If the number of rows affected is very large, you canapproach the limit that your operating system places on the maximumnumber of simultaneous locks. If this occurs, you may want to reduce thescope of the UPDATE statement, or lock the entire table before executingthe statement.

See the section “Locking” in Chapter 3 for a more detailed description oftable-level and row-level locking in INFORMIX-4GL.

10. You cannot perform an UPDATE through a DECLAREd cursor thatincludes aggregate functions. The cursor can only specify simple columnnames.

11. The UNIQUE keyword cannot appear in a subquery within an UPDATEstatement.

Caution: If INFORMIX-4GL encounters an error while performing an UPDATE,the operation stops. Unless you have created the database with transactions, all data-base changes made up to the point where the error is encountered remain, butsubsequent 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 aCHAR column, or attempting to insert numeric values that exceed the limits of thedata type of the column. For example, you cannot insert the integer 123456 into aSMALLINT column.

If you omit the WHERE clause, INFORMIX-4GL assumes that you want to updateevery row in the table.

7-208 INFORMIX-4GL Statement Syntax

Page 575: Manual Informix

UPDATE

ExamplesUPDATE stock

SET unit_price = unit_price * 1.04WHERE manu_code = "HRO"

UPDATE customer SET * = p_customer.*WHERE customer_num = p_customer.customer_num

UPDATE customerSET (fname, company, address2) =

("Marie", "Marie’s Sports","P. O. Box 3621")

WHERE customer_num = 103

UPDATE table1SET (col1, col2, col3) =

((select min (ship_charge),max (ship_charge) from orders),"07/01/1986")

WHERE col4 = 1001

Related StatementsSELECT, DELETE, INSERT

INFORMIX-4GL Statement Syntax 7-209

Page 576: Manual Informix

UPDATE STATISTICS

UPDATE STATISTICS

OverviewUse the UPDATE STATISTICS statement to cause the number of rows in a tableto be recorded in the systables catalog.

SyntaxUPDATE STATISTICS [ FOR TABLE table-name ]

ExplanationUPDATE STATISTICS are required keywords.

FOR TABLE are optional keywords you use when you want toupdate the statistics for a single table.

table-name is the name of the table for which you want thestatistics updated.

Notes1. UPDATE STATISTICS is effective only when there is a current database.

2. INFORMIX-4GL uses the data generated by UPDATE STATISTICS to opti-mize searching strategy. When you have modified a table extensively, useUPDATE STATISTICS to improve the efficiency of queries.

3. INFORMIX-4GL does not update the statistics unless you execute theUPDATE STATISTICS statement.

4. If you omit the FOR TABLE clause, UPDATE STATISTICS updates all thetables in the current database.

Related StatementSET EXPLAIN

INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

7-210 INFORMIX-4GL Statement Syntax

Page 577: Manual Informix

VALIDATE

VALIDATE

OverviewUse the VALIDATE statement to determine whether values in a list of vari-ables conform to the allowed ranges of values in syscolval for a correspond-ing list of columns.

SyntaxVALIDATE variable-list LIKE column-list

ExplanationVALIDATE is a required keyword.

variable-list is a list of one or more variables, separated by commas.

LIKE is a required keyword.

column-list is a list of column names, preceded by table names and sep-arated by commas.

Notes1. 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 ofthe table (owner. table-name). You must specify owner when you refer to atable 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 includeit in a statement. See the section “Owner Naming” in Chapter 3 for moreinformation.

4. You can use the upscol utility to create and update the values insyscolval. (See the discussion of “The upscol Utility” in Appendix E.)

5. If the current database is not MODE ANSI, the upscol utility creates a sin-gle syscolval table that specifies acceptable values or ranges of values forany or all columns in the database. The VALIDATE statement comparesvariable-list with the limitations specified in this table.

INFORMIX-4GL Statement Syntax 7-211

Page 578: Manual Informix

VALIDATE

6. In a MODE ANSI database, each user of upscol creates an individualowner. syscolval table. When it executes the VALIDATE statement, INFOR-MIX-4GL compares each component of variable-list to the syscolval tablethat belongs to the owner of the corresponding table-name.column-name incolumn-list. (You can omit the owner prefix from table-name if the user whocompiled the current 4GL program is the owner of table-name.)

If the owner. syscolval table does not exist, the VALIDATE statement takesno action.

7. If the values of the components of variable-list do not conform entirelywith the INCLUDE values of syscolval, INFORMIX-4GL sets the statusvariable to a negative value. You must test the variables individually todetect 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.

ExamplesVALIDATE var1, var2, var3

LIKE tab1.col1, tab1.col2, tab1.col3

VALIDATE p_customer.* LIKE customer.*

Related StatementINITIALIZE

7-212 INFORMIX-4GL Statement Syntax

Page 579: Manual Informix

WHENEVER

WHENEVER

OverviewUse the WHENEVER statement to trap errors and other exceptional conditionsthat result during the execution of other 4GL statements.

SyntaxWHENEVER { ERROR | WARNING | NOT FOUND }

{GOTO [ : ] label | CALL function-name | CONTINUE | STOP }

ExplanationWHENEVER is a required keyword.

ERROR is a keyword to test for an error (status < 0) after each 4GLstatement. Its synonym SQLERROR conforms to the ANSIstandard for SQL syntax.

WARNING is a keyword to test for a warning (SQLAWARN[1] is set to W)after each 4GL statement. Its synonym is SQLWARNING.

NOT FOUND are keywords to test whether a FETCH is attempted beyondthe first or last row in the active set, or if no more rows satisfythe current SELECT statement (status=100).

GOTO is an optional keyword. Its synonym GO TO conforms to theANSI standard for SQL syntax.

: is an optional prefix to label, and conforms to the ANSI stan-dard for SQL syntax.

label is a statement label to which program control transfers whenthe specified exceptional condition occurs.

CALL is an optional keyword.

function-name is the name of a function to which program control transferswhen the exceptional condition occurs.

CONTINUE is an optional keyword, instructing INFORMIX-4GL to takeno action. You can use this option to turn off a previouslyspecified option.

STOP is an optional keyword, instructing INFORMIX-4GL to exitfrom the program immediately.

INFORMIX-4GL Statement Syntax 7-213

Page 580: Manual Informix

WHENEVER

Notes1. The WHENEVER statement is shorthand for putting an IF statement after

every SQL statement and form-related INFORMIX-4GL statement, andtesting 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 declareddatabase (that is, the database specified in the DATABASE statement thatprecedes the MAIN program block or the first FUNCTION or REPORT rou-tine of the module) as the current database and determines whether it isMODE ANSI.

If (at compile time) the database is MODE ANSI, the default for WHEN-EVER ERROR is CONTINUE. Otherwise, the default is STOP. No DATABASEor START DATABASE statement in a function has any effect on the WHEN-EVER ERROR default.

3. A program can include several WHENEVER statements. If they refer to thesame exception condition (ERROR, WARNING, or NOT FOUND), the lastone encountered takes precedence.

4. The scope of a WHENEVER statement is the file in which it occurs, andfrom its position in the file to the next WHENEVER statement for the sameexception condition in the same file. The scope extends to the end of thefile, if you do not specify more WHENEVER statements for the sameexception condition.

5. INFORMIX-4GL provides useful information (like source-file line num-bers where an error has occurred) when it terminates a program becauseof an error. You may want to allow errors to occur during program devel-opment and insert trapping at a later stage.

6. If the NOT FOUND condition (status=100) is returned, the open cursor isautomatically closed.

7. The label or :label specified after the GOTO or GO TO keywords must be inthe same routine (that is, the same FUNCTION, REPORT, or MAIN programblock) as the WHENEVER statement.

8. Some errors cannot be trapped by the WHENEVER ERROR statement. Cer-tain errors always terminate the program, and others result in action byINFORMIX-4GL prior to the action specified by WHENEVER. (If you alsohave the INFORMIX-4GL Interactive Debugger, however, you can exam-ine the current execution stack and the values of program variables afterany 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

Page 581: Manual Informix

WHENEVER

with status, and use NOT FOUND (two words) with the WHENEVERstatement.

ExamplesThe following statement executes a function called error_recovery if an errorcondition 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 con-trol, 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 theANSI 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 StatementsCALL, DEFER, FOREACH, GOTO, IF, LABEL

INFORMIX-4GL Statement Syntax 7-215

Page 582: Manual Informix

WHILE

WHILE

OverviewUse the WHILE statement to execute a group of statements while a conditionis TRUE.

SyntaxWHILE Boolean-expr

statement. . .[ EXIT WHILE ]. . .[ CONTINUE WHILE ]. . .

END WHILE

ExplanationWHILE is a required keyword.

Boolean-expr is an expression that can be either true or false.

statement is an INFORMIX-4GL statement (including anotherWHILE statement).

EXIT WHILE is an optional statement.

CONTINUE WHILE is an optional statement.

END WHILE are required keywords that terminate a WHILEstatement.

Notes1. The CONTINUE WHILE statement interrupts the sequence and causes the

program control to return to the top of the sequence and to test the Bool-ean-expr.

2. The EXIT WHILE statement interrupts the sequence and causes the pro-gram control to jump to the first statement following the END WHILEkeywords.

3. If Boolean-expr is FALSE on entry to the WHILE statement, program con-trol passes directly to the statement following END WHILE.

7-216 INFORMIX-4GL Statement Syntax

Page 583: Manual Informix

WHILE

Related StatementsCONTINUE, EXIT, FOR

INFORMIX-4GL Statement Syntax 7-217

Page 584: Manual Informix

The SELECT Statement

7

The SELECT Statement

OverviewUse the SELECT statement to query the current database.

The SELECT statement can include the following eight clauses. Of these, onlythe SELECT clause and the FROM clause are required. If the INTO clause ispresent, it must precede the FROM clause.

SyntaxSELECT 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 thelogical operators AND, OR, or NOT. A search condition can be any of the fol-lowing 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 joinedtables)

-218 INFORMIX-4GL Statement Syntax

Page 585: Manual Informix

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

ExplanationThe following pages explain each of the syntax elements. A few basic con-cepts 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 arithmeticoperators:

Operator Operation+ addition- subtraction* multiplication/ division

Note: Unlike INFORMIX-4GL statements, SQL statements cannot containexpressions that use the exponentiation (**) or modulus ( mod ) operators.

The result of the operation must make sense. For example, you cannotdivide 16 by Jones .

Column names in expressions must have an ‘‘at sign’’ ( @ ) in front ofthem if there is danger of confusion with program variables that have thesame 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 dateand the time of day. USER returns a string containing the login name ofthe 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 lengthfunctions. You cannot include both an aggregate function and a column

INFORMIX-4GL Statement Syntax 7-219

Page 586: Manual Informix

The SELECT Statement

in an expression. The functions that you can use in SQL statements aredefined at the end of this chapter.

A CHAR column can have subscripts so that only a portion of the columnvalue is involved in the expression. The notation for subscripting a col-umn is column-name[m, n], where you want the mth through the nth char-acters in the column, for m less than or equal to n. Here the brackets areliteral characters, not conventional symbols to indicate an option.

2. A relational operator is one of the following:

Operator Operation= equal to!= or < > 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 collatingorder, where lowercase letters are after uppercase letters, and both areafter numerals. See Appendix H for the ASCII codes of all the characters.

For DATE and DATETIME expressions, greater than means ‘‘later in time.’’

Notes1. The clauses of the SELECT statement are explained in detail on the follow-

ing pages. Briefly, SELECT names a list of columns or expressions to beretrieved, INTO names the program variables to receive the data, FROMnames a list of tables, WHERE sets conditions on the rows, GROUP BYgroups rows together, HAVING sets conditions on the groups, ORDER BYsequences the selected rows, and INTO TEMP puts the results into a tem-porary table.

2. If the SELECT statement returns no rows, INFORMIX-4GL returns a ‘‘norows found’’ code (status = NOTFOUND = 100). See Chapter 3 for a fullexplanation.

3. If a SELECT statement returns more than one row or if it is dynamicallydefined, you must use a cursor to FETCH one row at a time (seeChapter 3).

4. It is sometimes helpful to think of the SELECT statement in the followingway:

When you list more than one table in the FROM clause, INFORMIX-4GLbehaves as though it were creating a composite table that is the Cartesianproduct of all the tables in the FROM clause. That is, the rows of the newtable are constructed by taking all the possible combinations of rows from

7-220 INFORMIX-4GL Statement Syntax

Page 587: Manual Informix

The SELECT Statement

all the tables listed in the FROM clause. If there is a WHERE clause, INFOR-MIX-4GL eliminates from this new table all rows that do not meet the con-ditions of the WHERE clause. This modified table is returned to theSELECT clause, where all columns not listed are eliminated. The resultingtable is what the SELECT statement returns.

5. The SELECT statement cannot appear in a multi-statement PREPARE.

INFORMIX-4GL Statement Syntax 7-221

Page 588: Manual Informix

SELECT Clause

SELECT Clause

OverviewUse the SELECT clause to specify the data that you want to retrieve from oneor more tables in a database.

SyntaxSELECT [ ALL | DISTINCT | UNIQUE ] select-list

ExplanationSELECT is a required keyword.

ALL is a keyword that causes INFORMIX-4GL to select all rowsthat satisfy the WHERE clause, without eliminating dupli-cates. This keyword is the default.

DISTINCT is a keyword that causes INFORMIX-4GL to eliminate dupli-cate rows from the query results.

UNIQUE is a keyword that is synonymous with DISTINCT.

select-list is a list of column names and/or expressions separated bycommas. A column name must be unambiguous; use itstable name as a prefix if there can be confusion.

Notes1. 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 aquery or subquery.

3. You can use the asterisk (*) in the select-list to select all columns from allthe tables and views in the FROM clause. You could produce the sameresult 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 nota-tion tablename.*.

5. You can supply a display label for the column name or an expression in theselect-list by following the column name or expression with a legal identi-fier. If you create a temporary table with the INTO TEMP clause, the

7-222 INFORMIX-4GL Statement Syntax

Page 589: Manual Informix

SELECT Clause

column names of the temporary table are the display labels, if they havebeen defined.

6. If you specify an aggregate function and a column in the select-list, the col-umn must be used in the GROUP BY list (see “GROUP BY Clause” forfurther explanation).

ExamplesThe following examples use INTO, FROM, and WHERE clauses, whose syntaxwill be defined later.

This example selects columns customer_num, lname, and city; the FROMclause indicates that these columns are taken from the customer table. Thevalues returned are placed in the program variables cnum, lname, and town,respectively. Since lname is both a program variable name and a columnname, the column identifier is prefixed with the at ( @ ) sign.

SELECT customer_num, @lname, cityINTO cnum, lname, townFROM customer

The next statement counts the number of rows in orders in which thecustomer_num column contains the value 101. In other words, it counts thenumber of orders made by the customer whose identifying number is 101.The number is placed in the variable num.

SELECT COUNT(*)INTO numFROM ordersWHERE customer_num = 101

The next statement computes the average of the total_price values in thoserows of items that contain an order_num column equal to 1021.

SELECT AVG(total_price)FROM itemsWHERE order_num = 1021

The next example illustrates the use of display labels. It selects the sum of col-umns a and b from tablez and gives the sum the label abtotal. Similarly, theproduct of columns c and d is labeled cdprod.

SELECT a+b abtotal, c*d cdprodFROM tablezINTO TEMP x

INFORMIX-4GL Statement Syntax 7-223

Page 590: Manual Informix

INTO Clause

INTO Clause

OverviewUse the INTO clause to specify the program variables to receive the dataretrieved by the SELECT statement.

SyntaxINTO variable-list

ExplanationINTO is a required keyword.

variable-list is a list of program variables that should agree in order andtype with the corresponding columns or expressions in theselect-list.

Notes1. If the SELECT statement stands alone (not in a DECLARE statement), it

must be a singleton SELECT (returning exactly one row) and must have anINTO clause.

2. If the SELECT statement returns more than one row, you must use a cursorto FETCH the rows one at a time. (See Chapter 3.) You can put the INTOclause in the FETCH statement, rather than in the SELECT statement, butnot in both. You can use the FOREACH statement in place of the FETCHstatement.

3. If you use DECLARE to associate a SELECT statement with a cursor, theSELECT statement can specify individual elements as a constant but notas a variable of a program array. (FETCH or FOREACH statements canspecify program array elements as constants or variables in their INTOclause.)

4. If the number of variables in variable-list differs from the number of itemsin the select-list, INFORMIX-4GL returns a warning by settingSQLCA. SQLAWARN [4] to W. The actual number of variables transferred isthe lesser of the two numbers.

5. If possible, INFORMIX-4GL converts the data type of each selected item tomatch that of the receiving variable. If the conversion is not possible, anerror occurs and a negative value is returned in status. In this case, the

7-224 INFORMIX-4GL Statement Syntax

Page 591: Manual Informix

INTO Clause

value in the program variable is unpredictable. See Chapter 2 for a discus-sion of data conversion.

6. You cannot PREPARE a query that has an INTO clause. (Instead, you canDECLARE a cursor to perform the query.)

ExamplesThe following are equivalent program fragments:

DECLARE q_curs CURSOR FORSELECT @lname, @companyINTO lname, companyFROM customer

OPEN q_cursFETCH q_curs

DECLARE q_curs CURSOR FORSELECT @lname, @companyFROM customer

OPEN q_cursFETCH q_curs

INTO lname, company

DECLARE q_curs CURSOR FORSELECT @lname, @companyFROM customer

FOREACH q_curs INTO lname, company. . .

INFORMIX-4GL Statement Syntax 7-225

Page 592: Manual Informix

FROM Clause

FROM Clause

OverviewUse the FROM clause to specify the table(s) or views from which you want toselect data.

SyntaxFROM { table-name [ table-alias ] |

OUTER table-name [ table-alias ] |OUTER ( table-expr ) } [ , . . . ]

ExplanationFROM is a required keyword.

OUTER is an optional keyword.

table-name is the name or synonym of a table or view in which to searchfor data.

table-alias is an optional alias for table-name.

(table-expr) is one or more of the options in the preceding syntax,enclosed in parentheses (for example tab1, outer tab2 ).

Notes1. Use the optional keyword OUTER to form outer joins. See the “Outer

Joins” section in Chapter 3 and Appendix G, “Outer Joins,” for a discus-sion of this syntax.

2. In a database created as MODE ANSI, the name of a table or view is qual-ified by the username of the owner (owner.table-name). You must specifyowner 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 MODEANSI. INFORMIX-4GL checks the accuracy of owner, however, if youinclude it in a statement. See the section “Owner Naming” in Chapter 3of this manual.

3. You can specify an alias for a table name by following the table name witha space and an SQL identifier. This feature is especially useful when per-forming self-joins. (See the “WHERE Clause” section of this chapter.)

7-226 INFORMIX-4GL Statement Syntax

Page 593: Manual Informix

FROM Clause

4. The table-alias that you can specify in a FROM clause is distinct from thealias for a table that is sometimes required in the TABLES section of a formspecification file. An alias that you define in a form can appear in 4GLscreen interaction statements that reference screen fields but cannotappear in a SELECT statement. (See Chapter 4.)

ExamplesThe following example selects customers who have placed orders.

SELECT fname, lname, order_numFROM customer, ordersWHERE customer.customer_num =

orders.customer_num

The following example selects all customers whether or not they have placedorders.

SELECT fname, lname, order_numFROM customer, OUTER ordersWHERE customer.customer_num =

orders.customer_num

INFORMIX-4GL Statement Syntax 7-227

Page 594: Manual Informix

WHERE Clause

WHERE Clause

OverviewUse the WHERE clause to specify search criteria and join conditions on thedata to be selected.

SyntaxWHERE condition

ExplanationWHERE is a required keyword.

condition is a collection of one or more search conditions, optionallyconnected by the logical operators AND, OR, or NOT. A searchcondition can be any of the following:

• 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 condi-tions can be preceded by the keyword NOT, in which case the row is selectedonly if the condition that NOT qualifies is FALSE.

Syntax

expr rel-op expr

7-228 INFORMIX-4GL Statement Syntax

Page 595: Manual Informix

WHERE Clause

Explanation

expr is an expression.

rel-op is a relational operator.

Examples

SELECT fname, lname, companyFROM customerWHERE city[1,3] = "San"

SELECT order_num, companyFROM orders o, customer cWHERE 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 locatethat row if you use relational operators. For example, if paid_date has a NULLvalue, you cannot use either statement (a) or (b) to retrieve that row:

--(a)SELECT customer_num, order_date

FROM ordersWHERE paid_date = ""

--(b)SELECT customer_num, order_date

FROM ordersWHERE NOT paid_date != ""

You must use the syntax that follows:

SELECT customer_num, order_dateFROM ordersWHERE paid_date IS NULL

Syntax

expr [ NOT ] BETWEEN expr AND expr

Explanation

expr is an expression.

NOT is a keyword that indicates that the expression to the left liesoutside the range.

BETWEEN is a keyword that indicates that the value of the expressionto its left lies in the inclusive range of the values of the twoexpressions to its right.

INFORMIX-4GL Statement Syntax 7-229

Page 596: Manual Informix

WHERE Clause

AND is a required keyword.

Examples

SELECT stock_num, manu_codeFROM stockWHERE unit_price BETWEEN

loprice AND hiprice

SELECT UNIQUE customer_num, stock_num, manu_codeFROM orders, itemsWHERE order_date

BETWEEN "6/1/86" AND "9/7/89"AND orders.order_num = items.order_num

SELECT fname, lnameFROM customerWHERE zipcode NOT

BETWEEN "94100" AND "94199"

Syntax

expr [ NOT ] IN ( value-list )

Explanation

expr is an expression.

NOT is an optional keyword.

IN is a required keyword.

(value-list) is a list of values (enclosed in parentheses).

Notes

1. The search condition is satisfied when the expression to the left isincluded in the list of items. The NOT option produces a search conditionthat is satisfied when expr is not in the list of items.

2. The value-list can contain program variables, constants, or the special key-word constants TODAY, CURRENT, and USER.

3. TODAY is evaluated at execution time. CURRENT is evaluated when a cur-sor is opened, or when the query is executed if it is a singleton select.

7-230 INFORMIX-4GL Statement Syntax

Page 597: Manual Informix

WHERE Clause

Examples

SELECT lname, fname, companyFROM customerWHERE state IN ("CA", "WA", "OR")

SELECT item_num, total_priceINTO inum, tpriceFROM itemsWHERE manu_code IN

("HRO", "HSK")

Syntax

column-name [ NOT ] LIKE "string" [ ESCAPE "escape-character" ]

Explanation

column-name is the name of a column.

NOT is an optional keyword.

LIKE is a required keyword.

string is a pattern of characters enclosed in quotation marks.

ESCAPE is an optional keyword.

escape-character is a single character enclosed in quotation marks.

Notes

1. The search condition is successful when the value of the column on theleft matches the pattern specified by string. You can use wildcard charac-ters 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 columnon the left does not match the pattern specified by string.

3. The purpose of the ESCAPE clause is to permit the specification of anunderscore ( _ ) or the percent sign ( % ) in string, and to avoid their inter-pretation 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 thestring stands for the character % (not the wildcard). Finally, the characterszz in the string stand for the single character z.

INFORMIX-4GL Statement Syntax 7-231

Page 598: Manual Informix

WHERE Clause

4. You can only use the double quote ( " ) within string to match a literalquote; you cannot use the ESCAPE keyword. Similarly, you cannot use thequote character as the ESCAPE character in matching any other pattern.

Examples

SELECT fname, lnameFROM customerWHERE lname LIKE "%son"

finds every customer representative whose last name ends in son.

SELECT stock_num, manu_code, unit_priceFROM stockWHERE description LIKE "%ball%"

obtains stock number, manufacturer’s code, and unit price for all stock itemswith ball anywhere in their description.

SELECT * FROM customerWHERE company LIKE "%z_%" ESCAPE "z"

retrieves rows from the customer table where the company column valueincludes the underscore character.

Syntax

column-name [ NOT ] MATCHES "string" [ ESCAPE "escape-character" ]

Explanation

column-name is the name of a column.

NOT is an optional keyword.

MATCHES is a required keyword.

string is a pattern of characters enclosed in quotation marks.

ESCAPE is an optional keyword.

escape-character is a single character enclosed in quotation marks.

Notes

1. The search condition is successful when the value of the column on theleft matches the pattern specified by string. You can use the followingwildcard characters in place of other characters in the string:

* matches zero or more characters

? matches any single character

7-232 INFORMIX-4GL Statement Syntax

Page 599: Manual Informix

WHERE Clause

[...] matches any of the enclosed characters, including characterranges as in [a-z]. A caret ( ^ ) as the first character within thebrackets 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 columnon the left does not match the pattern specified by string.

3. The MATCHES comparison is an Informix Software extension to retaincompatibility 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 ques-tion mark ( ? ), an asterisk ( * ), the backslash ( \ ), and left or right bracket( [ ] ), in string and to avoid their interpretation as wildcards. If z is theescape 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 sin-gle character z (same as \z).

6. You can only use the double quote ( " ) within string to match a literalquote; you cannot use the ESCAPE keyword. Similarly, you cannot use thequote character as the ESCAPE character in matching any other pattern.

Examples

SELECT fname, lnameFROM customerWHERE lname MATCHES "Richard*"

selects rows in which the first seven letters of the last name are Richard (thusmatching Richard, Richards, Richardson, and any others).

SELECT customer_num, companyFROM customerWHERE city MATCHES "[A-J]*"

provides the customer number and company name for all customers in citiesthat start with the letters A through J.

SELECT * FROM customerWHERE company MATCHES "*z?*" ESCAPE "z"

retrieves rows from the customer table, where the value in the companycolumn includes the question mark.

INFORMIX-4GL Statement Syntax 7-233

Page 600: Manual Informix

WHERE Clause

Syntax

column-name IS [ NOT ] NULL

Explanation

column-name is the name of a column.

IS NULL are required keywords.

NOT is an optional keyword.

Examples

SELECT order_num, customer_numFROM ordersWHERE paid_date IS NULL

lists those order numbers and customer numbers where the order has notbeen paid.

You can link any number of the above-described conditions together usingthe logical operators AND or OR. For example:

SELECT order_num, total_priceFROM itemsWHERE total_price > loprice AND

manu_code LIKE "H%"

SELECT lname, customer_numFROM customerWHERE 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 clausebetween at least one column from one table and at least one column fromanother table. The effect of the join is to create a temporary composite tablein which each pair of rows (one from each table) satisfying the join conditionis linked together to form a single row.

7-234 INFORMIX-4GL Statement Syntax

Page 601: Manual Informix

WHERE Clause

Syntax

The critical elements of a SELECT statement with a join between two tables orviews table1 and table2 follow:

SELECT clause FROM table1, table2 WHERE condition

Explanation

SELECT clause is any valid SELECT clause involving columns from table1 ortable2.

FROM is a required keyword.

table1 is the name or synonym of one of the tables or views in thejoin.

table2 is the name or synonym of the other table or view in the join.

WHERE is a required keyword.

condition is any of the comparison conditions that involves columnsfrom both table1 and table2.

Notes

1. When columns from different tables have the same name, you must dis-tinguish them by prefixing the table identifier and a period, in the formattable.column.

2. In a database created as MODE ANSI, the name of a table is qualified bythe owner of the table (owner. table-name). You must specify owner whenyou 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 ina statement. See the section “Owner Naming” in Chapter 3 of thismanual.

3. A multiple join is a join of more than two tables. Its structure is similar tothat shown previously, except that you have a join condition for morethan 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 thetable 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 notthe join condition is met. If the join condition is not met, the columns fromtable2 in the select-list are set to NULL values. You indicate an outer join byinserting the keyword OUTER before table2.

INFORMIX-4GL Statement Syntax 7-235

Page 602: Manual Informix

WHERE Clause

Examples

This example specifies a two-table join:

SELECT order_num, lname, fnameFROM customer, ordersWHERE customer.customer_num

= orders.customer_num

The query results list the order number and first and last names of the cus-tomer’s representative for each order.

This example specifies a multiple-table join:

SELECT UNIQUE company, stock_num, manu_codeFROM customer c, orders o, items iWHERE 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 itemidentified 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 yWHERE x.unit_price > 2.5 * y.unit_price

This query finds pairs of stock items whose unit prices differ by a factorgreater than two and one-half. Here x and y are each aliases for the stocktable.

This example specifies an outer join:

SELECT company, order_numFROM customer c, OUTER orders oWHERE c.customer_num = o.customer_num

This query lists all the customers’ company names and order numbers, if thecustomer 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 informationabout outer joins.

7-236 INFORMIX-4GL Statement Syntax

Page 603: Manual Informix

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 anotherSELECT statement

• Ask whether any rows are selected by another SELECT statement

SELECT statements within a WHERE clause are called subqueries. A subquerycan return a single value, no values, or a set of values. If a subquery returnsa value, it must return only a single row or column. If the subquery does notreturn a value (for example, with the EXISTS keyword), any number of rowsand columns can be returned. A subquery cannot contain an ORDER BYclause.

The subquery can depend on whether the current row is being evaluated bythe 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.

expr is an expression.

rel-op is a relational operator.

ALL is a keyword to specify that the subquery can return zero, one, ormore values, and that the search condition is TRUE if the compar-ison is TRUE for each of the values returned. If the subqueryreturns no value, the search condition is TRUE.

ANY is a keyword to specify that the subquery can return zero, one, ormore values and that the search condition is TRUE if the compari-son is TRUE for at least one of the values returned. If the subqueryreturns no value, the search condition is FALSE.

SOME is a synonym for ANY.

INFORMIX-4GL Statement Syntax 7-237

Page 604: Manual Informix

WHERE Clause

IN is a keyword that asks whether expr is among the values returnedby the following SELECT-statement.

EXISTS is a keyword that asks whether any rows are returned by the fol-lowing SELECT-statement. The search condition is TRUE if the sub-query returns one or more rows.

NOT is an optional keyword that reverses the truth value of the searchcondition. Rows are selected if the WHERE condition is FALSE.

Notes

1. You can omit the keywords ANY and ALL in a comparison if you knowthat the subquery will return exactly one value. In this case, the searchcondition is TRUE if the comparison is TRUE for the expression and thevalue returned by the subquery. The status will be set to a negative num-ber 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_numFROM itemsWHERE stock_num = 9 AND quantity =

(SELECT MAX(quantity) FROM itemsWHERE stock_num = 9)

This subquery returns a single value (the maximum number of volleyballnets ordered) to the outer-level query. The entire SELECT statement lists theorder numbers for orders that include the maximum number of volleyballnets.

SELECT UNIQUE order_numFROM itemsWHERE total_price > ALL

(SELECT total_priceFROM itemsWHERE order_num = 1011)

7-238 INFORMIX-4GL Statement Syntax

Page 605: Manual Informix

WHERE Clause

This query lists the order numbers of all orders containing an item whosetotal price is greater than the total price on all the items in order number 1011.

SELECT UNIQUE customer_numFROM ordersWHERE order_num NOT IN

(SELECT order_numFROM items

WHERE stock_num = 1)

This query lists all customer numbers of customers who have placed ordersthat do not include baseball gloves (stock_num = 1).

SELECT order_num, stock_num, manu_code, total_priceFROM items xWHERE total_price >

(SELECT 2 * MIN(total_price)FROM itemsWHERE order_num = x.order_num)

This query (using a correlated subquery) lists all items whose total price is atleast twice the minimum total price for all items on the same order.

INFORMIX-4GL Statement Syntax 7-239

Page 606: Manual Informix

GROUP BY Clause

GROUP BY Clause

OverviewUse 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.

SyntaxGROUP BY group-list

ExplanationGROUP BY are required keywords.

group-list is a column name or a list of column names, separated bycommas, that determines the group. The query result con-tains a single row for each set of rows that satisfies theWHERE clause and contains a unique value or set of valuesin the column or columns indicated by group-list.

Notes1. Using a GROUP BY clause restricts what you can enter in the SELECT

clause. The select-list can include aggregate functions for any columnand/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 alsolist 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 inte-gers that refer to the position of items in the select-list.

4. NULL values are considered identical when evaluated within a GROUP BYclause.

5. You can GROUP BY up to eight columns.

ExamplesSELECT order_num, COUNT(*), SUM(total_price)

FROM itemsGROUP BY order_num

7-240 INFORMIX-4GL Statement Syntax

Page 607: Manual Informix

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 itemsGROUP BY 1

returns the same information as the previous example.

INFORMIX-4GL Statement Syntax 7-241

Page 608: Manual Informix

HAVING Clause

HAVING Clause

OverviewUse the HAVING clause to apply one or more qualifying conditions to groups.

SyntaxHAVING condition

ExplanationHAVING is a required keyword.

condition is a condition, as if defined for a WHERE clause.

Notes1. 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 youuse HAVING without GROUP BY, the HAVING clause applies to all rowsthat satisfy the WHERE clause. Without a GROUP BY clause, all rows thatsatisfy the WHERE clause make up a single group.

3. You can use the HAVING clause to place conditions on the GROUP BY col-umn values, as well as on aggregate values.

ExampleSELECT order_num, AVG(total_price)

FROM itemsGROUP BY order_numHAVING COUNT(*) > 2

This query returns the average total price per item on all orders that havemore than two items.

7-242 INFORMIX-4GL Statement Syntax

Page 609: Manual Informix

ORDER BY Clause

ORDER BY Clause

OverviewUse the ORDER BY clause to sort query results by the values contained in oneor more columns. You can sort only by a column that you specify in theSELECT clause.

SyntaxORDER BY column-name [ ASC | DESC ] [ , . . . ]

ExplanationORDER BY are required keywords.

column-name is the name of a column by which you want to sort the queryresults.

ASC is a keyword that specifies that the results should be inascending order (smallest value first, largest last). ASC is thedefault.

DESC is a keyword that specifies that the results should be indescending order (largest value first).

Notes1. 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 BYclause cannot be greater than 120 bytes.

4. In the place of column names, you can enter one or more integers thatrefer to the position of items in the select-list. In this way, you can ORDERBY an expression.

5. You cannot use a DECLARE statement with a FOR UPDATE clause to asso-ciate a cursor with a SELECT statement that has an ORDER BY clause.

INFORMIX-4GL Statement Syntax 7-243

Page 610: Manual Informix

ORDER BY Clause

ExamplesCORRECT: SELECT order_date, ship_date

FROM ordersORDER BY order_date

CORRECT: SELECT *FROM ordersORDER BY order_date

INCORRECT: SELECT order_date, ship_dateFROM ordersORDER BY customer_num

In the first two examples, order_date is either explicitly or implicitly listed inthe select-list. In the third example, even though the column customer_numis in the orders table, it was not contained in the select-list.

The query in the next example

SELECT customer_num, fname, lname, companyFROM customerORDER BY 3, 2

performs a nested sort. The first level of sorting is based on the lname col-umn, and the second level is based on the fname column.

7-244 INFORMIX-4GL Statement Syntax

Page 611: Manual Informix

INTO TEMP Clause

INTO TEMP Clause

OverviewUse the INTO TEMP clause to create a temporary table that contains the queryresults. The temporary table disappears when your program ends.

SyntaxINTO TEMP table-name [ WITH NO LOG ]

ExplanationINTO TEMP are required keywords.

table-name is the SQL identifier that you assign to the temporary table.

WITH NO LOG are optional keywords to prevent logging of temporarytables.

Notes1. 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 andmore easily understood statements.

3. The column names of the temporary table are those named in the select-list. If you list a display label for a column or expression, the column namein 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, noresults will be returned to the program variables, and status will be set toa negative value.

6. The temporary table persists until you exit from your 4GL program orissue the DROP TABLE table-name statement.

7. The keywords WITH NO LOG prevent INFORMIX-4GL from including inthe transaction log operations on temporary tables. You can use thisoption to reduce the overhead of transaction logging.

INFORMIX-4GL Statement Syntax 7-245

Page 612: Manual Informix

UNION Operator

UNION Operator

OverviewThe UNION operator is a keyword placed between two SELECT statements, tolet you combine the queries into a single query.

SyntaxSELECT-statement UNION [ ALL ] SELECT-statement

[ UNION [ ALL ] SELECT-statement . . . ]

ExplanationUNION is a keyword that selects all rows from both queries, removes

duplicates, and returns what is left.

ALL is an optional keyword that leaves the duplicates.

Notes1. 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 compoundqueries constructed using the UNION operator. The advantage of theUNION operator is that it makes the process easier.

3. There are restrictions on the queries that you can connect with UNIONoperators.

• The number of the items in the select-list of each query must be thesame, and corresponding items in each select-list must have identicaldata types.

• Corresponding items need not have the same identifier.

7-246 INFORMIX-4GL Statement Syntax

Page 613: Manual Informix

UNION Operator

• You cannot use an INTO statement in a query unless you are sure thatthe compound query will return exactly one row and you are notusing a cursor. In this rare case, the INTO clause must be in the firstSELECT statement.

• If you use an ORDER BY clause, it must follow the last SELECT state-ment, and you must refer by integer, not by identifier, to the item to beordered. Ordering takes place after the set operation is complete.

4. UNION operators cannot occur inside a subquery and cannot be used inthe definition of a view.

5. The column names (or display labels) of the resulting table are the sameas those from the first SELECT statement.

6. You can put the results of a UNION into a temporary table by putting anINTO TEMP clause in the final SELECT statement.

ExampleThe following example selects those items (identified by a stock number anda manufacturing code) that have a unit price of less than $100.00 or that havebeen ordered in quantities greater than three.

SELECT DISTINCT stock_num, manu_codeFROM stockWHERE unit_price < 100.00

UNION

SELECT stock_num, manu_code,FROM itemsWHERE quantity > 3ORDER BY 1

INFORMIX-4GL Statement Syntax 7-247

Page 614: Manual Informix

Functions in SQL Statements

7

Functions in SQL StatementsYou can use the aggregate, length, date, and datetime functions anywhere inan SQL expression that a constant can appear. The following functions areavailable:

Aggregate Length Date DatetimeFunctions Functions Functions FunctionsCOUNT(*) LENGTH( ) DATE( ) CURRENTSUM( ) DAY( ) EXTEND( )AVG( ) MDY( )MAX( ) MONTH( )MIN( ) WEEKDAY( )

YEAR( )

These functions are defined on the pages that follow.

You can also use the TODAY and USER functions that are described inChapter 2 and Chapter 3 of this manual. Except for CURRENT, DATE( ), andMDY( ), all the date and datetime functions can accept both DATE andDATETIME values as arguments.

-248 INFORMIX-4GL Statement Syntax

Page 615: Manual Informix

Aggregate Functions

Aggregate Functions

OverviewThe aggregate functions take on values that depend on the set of rowsreturned by the WHERE clause of a SELECT statement. In the absence of aWHERE clause, the aggregate functions take on values that depend on all therows formed by the FROM clause.

Syntax Function

COUNT (*) returns the number of rows that satisfy theWHERE clause.

COUNT ( DISTINCT x) returns the number of different values in col-umn x from rows that satisfy the WHEREclause.

SUM ( [ ALL | DISTINCT ] x) returns the sum of all values in column xfrom rows that satisfy the WHERE clause. Youcan apply SUM only to number columns. Thedefault is ALL. If you use the keywordDISTINCT, the sum is only over distinct val-ues in column x.

AVG ( [ ALL | DISTINCT ] x) returns the average of all values in column xfrom rows that satisfy the WHERE clause. Youcan apply AVG only to number columns. Thedefault is ALL. If you use the keywordDISTINCT, the average (mean) is only over thedistinct values in column x.

MAX ( [ ALL | DISTINCT ] x) returns the largest value in column x from arow that satisfies the WHERE clause. Defaultis ALL.

MIN ( [ ALL | DISTINCT ] x) returns the lowest value in column x from arow that satisfies the WHERE clause. Defaultis ALL.

Notes1. In the functions SUM(x), AVG(x), MAX(x), and MIN(x), x can be an expres-

sion instead of a column name. If x is an expression, the function isevaluated over the values of the expression as computed for each row that

INFORMIX-4GL Statement Syntax 7-249

Page 616: Manual Informix

Aggregate Functions

satisfies the WHERE clause. The expression can not contain another aggre-gate function.

2. Both the COUNT(x) function and the keyword DISTINCT can only be usedwith column names, not with expressions.

3. You can use the keyword DISTINCT only once in each level of a query orsubquery. Use DISTINCT to disregard duplicate query results or to elimi-nate duplicates from the argument of an aggregate function.

4. Specifying DISTINCT in a MIN or MAX function has no effect on the valuereturned 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) ignorerows with NULL values for x and return the appropriate values basedon 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 returnNULL for that column.

• COUNT(*) counts all rows, even if the value of every column in therow is NULL.

ExamplesIf 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 val-ues, MAX (x) returns 4, and MIN (x) returns 2.

7-250 INFORMIX-4GL Statement Syntax

Page 617: Manual Informix

LENGTH( )

LENGTH( )

OverviewThe LENGTH function returns the clipped length of a character column orvariable.

SyntaxLENGTH ( string )

Explanationstring is a character variable, string constant, or the name of a column

that contains character data.

NoteLENGTH allows only one argument. You can, however, combine LENGTH val-ues through an expression. (See the example.)

ExampleSELECT 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 theINFORMIX-OnLine Programmer’s Manual for more information.

INFORMIX-4GL Statement Syntax 7-251

Page 618: Manual Informix

DATE( )

DATE( )

OverviewThe DATE( ) function returns a type DATE value, corresponding to the expres-sion with which you call it.

SyntaxDATE ( expr )

ExplanationDATE is a required keyword.

expr is a required expression that can be converted to a type DATEvalue.

NoteThe expr is usually of type CHAR, DATETIME, or INTEGER.

ExampleThe following example uses DATE( ) to convert a string to a date.

WHERE end_date > DATE("12/13/1989")

7-252 INFORMIX-4GL Statement Syntax

Page 619: Manual Informix

DAY( )

DAY( )

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

SyntaxDAY ( time-expr )

ExplanationDAY is a required keyword.

time-expr is a required expression whose value is of type DATE orDATETIME.

ExampleThis example uses the DAY ( ) function with the CURRENT function to com-pare column values to the current day of the month.

WHERE DAY(ord_date) > DAY(CURRENT)

INFORMIX-4GL Statement Syntax 7-253

Page 620: Manual Informix

MDY( )

MDY( )

OverviewThe MDY( ) function returns a type DATE value when you call it with threeexpressions that evaluate to integers representing the month, day of themonth, and year.

SyntaxMDY ( expr1, expr2, expr3 )

ExplanationMDY is a required keyword.

expr1 is an expression that evaluates to an integer representing the num-ber of the month (1-12).

expr2 is an expression that evaluates to an integer representing the num-ber of the day of the month (1-28, 29, 30, or 31, depending on themonth).

expr3 is an expression that evaluates to a four-digit integer representingthe year.

NotesThe value of expr3 cannot be the abbreviation for the year. For example, 89 isa year in the first century.

7-254 INFORMIX-4GL Statement Syntax

Page 621: Manual Informix

MONTH( )

MONTH( )

OverviewThe MONTH( ) function returns an integer corresponding to the month por-tion of its type DATE or DATETIME argument.

SyntaxMONTH ( time-expr )

ExplanationMONTH is a required keyword.

time-expr is a required expression of type DATE or DATETIME.

Notes1. 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.

ExampleSELECT order_num, MONTH (order_date) FROM orders

INFORMIX-4GL Statement Syntax 7-255

Page 622: Manual Informix

WEEKDAY( )

WEEKDAY( )

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

SyntaxWEEKDAY ( time-expr )

ExplanationWEEKDAY is a required keyword.

time-expr is a required expression of type DATE or DATETIME.

Notes1. 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.

ExamplesSELECT order_num, WEEKDAY (order_date) FROM orders

SELECT * FROM ordersWHERE WEEKDAY (paid_date) = WEEKDAY(CURRENT - 31 UNITS DAY)

7-256 INFORMIX-4GL Statement Syntax

Page 623: Manual Informix

YEAR( )

YEAR( )

OverviewThe YEAR( ) function returns an integer that represents the year when you callit with a type DATE or DATETIME expression.

SyntaxYEAR ( time-expr )

ExplanationYEAR is a required keyword.

time-expr is a required expression of type DATE or DATETIME.

NotesThe time-expr cannot be an INTERVAL argument.

ExamplesSELECT order_num, YEAR (order_date) FROM orders

SELECT order_num, customer_num FROM ordersWHERE YEAR(ship_date) < YEAR(TODAY)

The second example specifies rows in which the ship_date is earlier than thebeginning of the current year.

INFORMIX-4GL Statement Syntax 7-257

Page 624: Manual Informix

CURRENT

CURRENT

OverviewThe CURRENT function returns a DATETIME value with the date and time ofday of the current instant.

SyntaxCURRENT [ first TO last ]

ExplanationCURRENT is a required keyword.

first is a qualifier that specifies the first field to be returned.

TO is a required keyword if you specify first and last.

last is a qualifier that specifies the last field to be returned.

Notes1. 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 aDATETIME literal.

3. The first qualifier must specify a field that is more significant than or equalto the last qualifier.

4. If the function is executed more than once in a statement, identical valuesmay be returned at each point of the call. You cannot rely on CURRENT toprovide distinct values each time that it executes.

5. INFORMIX-4GL may not execute the CURRENT function in the physicalorder in which it appears in a statement. You should not use the functionto mark the start, the end, or any specific point in the execution of the 4GLstatement.

6. If no first TO last qualifiers are specified, the default qualifiers are YEARTO FRACTION(3).

7-258 INFORMIX-4GL Statement Syntax

Page 625: Manual Informix

CURRENT

7. The following qualifiers are valid:

Identifier Qualified DataYEAR A number of years.MONTH A number of months.DAY A number of days.HOUR A number of hours.MINUTE A number of minutes.SECOND A number of seconds.FRACTION (n) A decimal fraction of a second with n (up to five) digits of precision.

The default precision is three digits (thousandths of a second).

ExampleSELECT 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

Page 626: Manual Informix

EXTEND( )

EXTEND( )

OverviewThe EXTEND function adjusts the precision of a DATETIME or DATE value.

SyntaxEXTEND ( value [ , first TO last ] )

ExplanationEXTEND is a required keyword.

value is a DATETIME or DATE type column name, variable, orexpression.

first is an optional qualifier that specifies the first field in the result.(See Note 5.)

TO is a required keyword if you include first and last qualifiers.

last is an optional qualifier that specifies the last field in the result.(See Note 6.)

Notes1. 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 DATEvalue.)

2. If no first TO last qualifiers are specified, the default qualifiers are YEARTO FRACTION(3).

3. The first qualifier must specify a field that is more significant than or equalto the last qualifier.

4. If the value contains fields not specified by the qualifiers, the unwantedfields are discarded.

5. If the first qualifier specifies a field to the left of (that is, more significantthan) what exists in value, the new fields are filled with values returnedby the CURRENT function.

7-260 INFORMIX-4GL Statement Syntax

Page 627: Manual Informix

EXTEND( )

6. If the last qualifier specifies a field to the right of (that is, less significantthan) 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 HOURto FRACTION are filled in with 0.

7. The following qualifiers are valid:

Identifier Qualified DataYEAR A number of years.MONTH A number of months.DAY A number of days.HOUR A number of hours.MINUTE A number of minutes.SECOND A number of seconds.FRACTION (n) 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 DATETIMEvalue, you cannot combine the two values with the addition ( + ) or sub-traction ( - ) operators. Similarly, you cannot add or subtract a DATEvalue and an INTERVAL whose last qualifier is smaller than DAY.

In these cases, you must use the EXTEND function to return an adjustedDATETIME value on which to perform the arithmetic operation.

See also Appendix J, “Working with DATETIME and INTERVAL Data.”

ExamplesIn the following example, the EXTEND function returns the MONTH and DAYfields from a column that contains YEAR, MONTH, and DAY data. In thisinstance 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 aDATETIME column whose last qualifier is larger than MINUTE. Then theEXTEND function is required in the following statement, because theINTERVAL operand includes a field (MINUTE) that is not part of the precisionof air_date.

SELECT sponsor, prog_title, air_date FROM tv_programsWHERE air_date >= TODAYAND CURRENT > EXTEND(air_date) - 2880 UNITS MINUTE

INFORMIX-4GL Statement Syntax 7-261

Page 628: Manual Informix

EXTEND( )

Since no qualifiers are specified as arguments, the EXTEND function returnsa DATETIME value with the default precision YEAR to FRACTION(3). TheWHERE clause in this example specifies the rows in which air_date has avalue in a range from the beginning of the current day (TODAY) up to 48hours (= 2,880 minutes) after the current instant.

See also Appendix J, “Working with DATETIME and INTERVAL Data.” formore information about arithmetic operations on date and time data types.

7-262 INFORMIX-4GL Statement Syntax

Page 629: Manual Informix

Appendix

A

DemonstrationDatabase andApplication

The stores DatabaseThe stores database contains a set of tables that describe animaginary business. You can access the data in stores by thedemonstration programs that appear in this book, as wellas by application programs that are listed in the documen-tation of other Informix products. The stores database is notMODE ANSI.

This appendix contains five sections:

• The first section describes the structure of the tables inthe stores database. For each table, the name and thedata type of each column are listed. Any indexes onindividual columns or on multiple columns are identi-fied and classified as unique or as allowing duplicatevalues.

• The second section presents a graphic map of the tablesin the stores database, showing potential join columns.

• The third section discusses the join columns that linksome of the tables in the stores database, and illustrateshow you can use these relationships to obtain informa-tion from multiple tables.

• The fourth section shows the data contained in eachtable of the stores database.

Page 630: Manual Informix

Structure of the Tables

• The final section contains the form specifications, INFORMIX-4GL sourcecode modules, and help message source code for the demonstrationapplication.

If you have modified or deleted some or all of the data in these tables, youcan 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 currentdirectory, and places the stores database files there. It also copies all the dem-onstration programs, forms, and help files into the current directory.

Structure of the TablesThe stores database contains information about a fictitious sporting goodsdistributor that services stores in the Western United States. This databaseincludes 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, andthe name of its representative. The customer table has the following columns:

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)

The customer_num column is indexed as unique.

A-2 Demonstration Database and Application

Page 631: Manual Informix

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 dis-tributor. This information includes the order number, the date when theorder was made, the customer number, shipping instructions, the customer’spurchase order number, the date when the order was shipped, the weight ofthe order, the shipment charge, and the date when the customer paid for theorder. It also tells whether a backlog exists.

The columns of the orders table are listed here:

order_num serial(1001)order_date datecustomer_num integership_instruct char(40)backlog char(1)po_num char(10)ship_date dateship_weight decimal(8,2)ship_charge money(6)paid_date date

The order_num column is indexed, and must contain unique values. Thecustomer_num column is indexed, but allows duplicates.

The items Table

An order can include one or more items. The items table describes the itemsin each order. Information in the items table includes the item number, codesfor the order, stock, and manufacturer, the quantity, and the total price for theitem. The items table has these columns:

item_num smallintorder_num integerstock_num smallintmanu_code char(3)quantity smallinttotal_price money(8)

The order_num column has an index that allows duplicate values. A multi-ple-column index for the stock_num and manu_code columns also permitsduplicate values.

Demonstration Database and Application A-3

Page 632: Manual Informix

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 offersbasketballs from one manufacturer.

The stock table is a catalog of the items sold by the distributor. For each itemin stock, the stock table lists a stock number identifying the type of item, acode identifying the manufacturer, a description of the item, its unit price, theunit by which the item must be ordered, and a description of the unit (forexample, a case containing 10 baseballs).

These are the names and data types of the columns in the stock table:

stock_num smallintmanu_code char(3)description char(15)unit_price money(6)unit char(4)unit_descr char(15)

A multiple-column index for both the stock_num and manu_code columnsallows only unique values.

The manufact Table

Information about the five manufacturers whose sporting goods are handledby the distributor is kept in the manufact table. Each row contains a manu-facturer’s identifying code and name. The columns in the manufact table areas follows:

manu_code char(3)manu_name 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 statesof the United States. It includes two columns:

code char(2)sname char(15)

The code column is indexed as unique.

A-4 Demonstration Database and Application

Page 633: Manual Informix

Map of the stores Database

Map of the stores DatabaseFigure A-1 displays the column names of the tables in the stores database,and indicates which columns in different tables contain the sameinformation.

Figure A-1 Tables in the stores Database

Join Columns That Link the DatabaseThe tables of the stores database are linked together by join columns, whichare identified in this section. You can use them to retrieve and display infor-mation 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 howinformation 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, asshown in Figure A-2.

items

orders item_num

order_num order_num stock

customer order_date stock_num stock_num manufact

customer_num customer_num manu_code manu_code manu_code

fname ship_instruct quantity description manu_name

lname backlog total_price unit_price

company po_num unit

address1 ship_date unit_descr

address2 ship_weight

state city ship_charge

code state paid_date

sname zipcode

phone

Demonstration Database and Application A-5

Page 634: Manual Informix

Join Columns That Link the Database

Figure A-2 Tables Joined by the customer_num Column

The customer table contains a customer_num column that holds a numberidentifying a customer, along with columns for the customer’s name, com-pany, address, and telephone number. For example, the row with informa-tion about Anthony Higgins contains the number 104 in the customer_numcolumn.

The orders table also contains a customer_num column that stores the num-ber of the customer who placed a particular order. According to Figure A-2,customer 104 (Anthony Higgins) has placed two orders, since his customernumber appears in two rows of the orders table.

The join relationship lets you select information from both tables. This meansthat you can retrieve Anthony Higgins’s name and address and informationabout 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 con-tains an identification number for each order. If an order includes severalitems, the same order number appears in several rows of the items table.Figure A-3 shows this relationship.

customer table(detail)

orders table(detail)

customer_num fname lname101 Ludwig Pauli102 Carole Sadler103 Philip Currie104 Anthony Higgins

order_num order_date customer_num1001 01/20/1989 1041002 06/01/1989 1011003 10/12/1989 1041004 04/12/1989 106

A-6 Demonstration Database and Application

Page 635: Manual Informix

Join Columns That Link the Database

Figure A-3 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: thestock_num column stores a stock number for an item, and the manu_codecolumn stores a code to identify the manufacturer. You need both the stocknumber and the manufacturer code to uniquely identify an item. For exam-ple, the item with the stock number 1 and the manufacturer code HRO is aHero baseball glove, while the item with the stock number 1 and and themanufacturer code HSK is a Husky baseball glove.

order_num order_date customer_num1001 01/20/1989 1041002 06/01/1989 1011003 10/12/1989 1041004 04/12/1989 106

item_num order_num stock_num manu_code1 1001 1 HRO1 1002 4 HSK2 1002 3 HSK1 1003 9 ANZ2 1003 8 ANZ3 1003 5 ANZ

orders table(detail)

items table(detail)

Demonstration Database and Application A-7

Page 636: Manual Informix

Join Columns That Link the Database

Figure A-4 Tables Joined by Two Columns

The same stock number and manufacturer code can appear in more than onerow of the items table, if the same item belongs to separate orders. This isillustrated 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 stocktable if the manufacturer produces more than one piece of equipment. Thisrelationship is illustrated in Figure A-5.

Figure A-5 Tables Joined by the manu_code Column

item_num order_num stock_num manu_code1 1001 1 HRO1 1002 4 HSK2 1002 3 HSK1 1003 9 ANZ2 1003 8 ANZ3 1003 5 ANZ1 1004 1 HRO

stock_num manu_code description1 HRO baseball glove1 HSK baseball glove1 SMT baseball glove

items table(detail)

stock table(detail)

stock_num manu_code description1 HRO baseball glove1 HSK baseball glove1 SMT baseball glove2 HRO baseball

manu_code manu_nameNRG NorgeHSK HuskyHRO Hero

stock table(detail)

manufact table(detail)

A-8 Demonstration Database and Application

Page 637: Manual Informix

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 containsthe state code. This column is called code in the state table and state in thecustomer table. If several customers live in the same state, the same statecode will appear in several rows of the customer table, as shown in Figure A-6.

Figure A-6 Tables Joined by the State-Code Column

Joining lets you rearrange your view of a database whenever you want. Itprovides flexibility that lets you create new relationships between tableswithout redesigning the database. You can easily expand the scope of a data-base by adding new tables that join the existing tables. As you read throughthis manual, you will see programs that set up the join relationships acrosstables of the stores database. Refer to these figures whenever you need toreview these relationships.

Data in the stores DatabaseThe tables that follow display the data in the stores database.

customer table(detail)

state table(detail)

customer_num fname lname ... state101 Ludwig Pauli ... CA102 Carole Sadler ... CA103 Philip Currie ... CA

code snameAK AlaskaAL AlabamaAR ArkansasAZ ArizonaCA California

Demonstration Database and Application A-9

Page 638: Manual Informix

Data in the stores Database

cust

omer

Tab

le

cust

omer

_nu

mfn

ame

lnam

eco

mp

any

add

ress

1ad

dre

ss2

city

stat

ezi

p c

ode

ph

one

101

Lud

wig

Paul

iA

ll Sp

orts

Sup

plie

s21

3 E

rstw

ild C

ourt

Sunn

yval

eC

A94

086

408-

789-

8075

102

Car

ole

Sad

ler

Spor

ts S

pot

785

Gea

ry S

tSa

n Fr

anci

sco

CA

9411

741

5-82

2-12

89

103

Phili

pC

urri

ePh

il’s

Spor

ts65

4 Po

plar

P. O

. Box

349

8Pa

lo A

lto

CA

9430

341

5-32

8-45

43

104

Ant

hony

Hig

gins

Play

Bal

l!E

ast S

hopp

ing

Cnt

r.42

2 B

ay R

oad

Red

woo

d C

ity

CA

9402

641

5-36

8-11

00

105

Ray

mon

dV

ecto

rL

os A

ltos

Spo

rts

1899

La

Lom

a D

rive

Los

Alt

osC

A94

022

415-

776-

3249

106

Geo

rge

Wat

son

Wat

son

& S

on11

43 C

arve

r Pl

ace

Mou

ntai

n V

iew

CA

9406

341

5-38

9-87

89

107

Cha

rles

Rea

mA

thle

tic

Supp

lies

41 Jo

rdan

Ave

nue

Palo

Alt

oC

A94

304

415-

356-

9876

108

Don

ald

Qui

nnQ

uinn

’s S

port

s58

7 A

lvar

ado

Red

woo

d C

ity

CA

9406

341

5-54

4-87

29

109

Jane

Mill

erSp

ort S

tuff

May

fair

Mar

t73

45 R

oss

Blv

d.

Sunn

yval

eC

A94

086

408-

723-

8789

110

Roy

Jaeg

erA

A A

thle

tics

520

Topa

z W

ayR

edw

ood

Cit

yC

A94

062

415-

743-

3611

111

Fran

ces

Key

esSp

orts

Cen

ter

3199

Ste

rlin

g C

ourt

Sunn

yval

eC

A94

085

408-

277-

7245

112

Mar

gare

tL

awso

nR

unne

rs &

Oth

ers

234

Wya

ndot

te W

ayL

os A

ltos

CA

9402

241

5-88

7-72

35

113

Lan

aB

eatt

ySp

orts

tow

n65

4 O

ak G

rove

Men

lo P

ark

CA

9402

541

5-35

6-99

82

114

Fran

kA

lber

tson

Spor

ting

Pla

ce94

7 W

aver

ly P

lace

Red

woo

d C

ity

CA

9406

241

5-88

6-66

77

115

Alf

red

Gra

ntG

old

Med

al S

port

s77

6 G

ary

Ave

nue

Men

lo P

ark

CA

9402

541

5-35

6-11

23

116

Jean

Parm

elee

Oly

mpi

c C

ity

1104

Spi

nosa

Dri

veM

ount

ain

Vie

wC

A94

040

415-

534-

8822

117

Arn

old

Sipe

sK

ids

Kor

ner

850

Lytt

on C

ourt

Red

woo

d C

ity

CA

9406

341

5-24

5-45

78

118

Dic

kB

axte

rB

lue

Rib

bon

Spor

ts54

27 C

olle

geO

akla

ndC

A94

609

415-

655-

0011

A-10 Demonstration Database and Application

Page 639: Manual Informix

Data in the stores Database

items Table

item_num order_num stock_num manu_code quantity total_price

1 1001 1 HRO 1 250.01 1002 4 HSK 1 960.02 1002 3 HSK 1 240.01 1003 9 ANZ 1 20.02 1003 8 ANZ 1 840.03 1003 5 ANZ 5 99.01 1004 1 HRO 1 960.02 1004 2 HRO 1 126.03 1004 3 HSK 1 240.04 1004 1 HSK 1 800.01 1005 5 NRG 10 280.02 1005 5 ANZ 10 198.03 1005 6 SMT 1 36.04 1005 6 ANZ 1 48.01 1006 5 SMT 5 125.02 1006 5 NRG 5 190.03 1006 5 ANZ 5 99.04 1006 6 SMT 1 36.05 1006 6 ANZ 1 48.01 1007 1 HRO 1 250.02 1007 2 HRO 1 126.03 1007 3 HSK 1 240.04 1007 4 HRO 1 480.05 1007 7 HRO 1 600.01 1008 8 ANZ 1 840.02 1008 9 ANZ 5 100.01 1009 1 SMT 1 450.01 1010 6 SMT 1 36.02 1010 6 ANZ 1 48.01 1011 5 ANZ 5 99.01 1012 8 ANZ 1 840.02 1012 9 ANZ 10 200.01 1013 5 ANZ 1 19.82 1013 6 SMT 1 36.03 1013 6 ANZ 1 48.04 1013 9 ANZ 2 40.01 1014 4 HSK 1 960.02 1014 4 HRO 1 480.01 1015 1 SMT 1 450.0

Demonstration Database and Application A-11

Page 640: Manual Informix

Data in the stores Database

ord

ers

Tabl

e

ord

er_n

um

ord

er_d

ate

cust

omer

_nu

msh

ip_i

nst

ruct

bac

klo

gp

o_n

um

ship

_dat

esh

ip_w

eigh

tsh

ip_c

har

ge p

aid

_ d

ate

1001

01/

20/

8910

4up

sn

B77

836

02/

01/

8920

.40

10.0

003

/22

/89

1002

06/

01/

8910

1po

on

box;

n92

7006

/06

/89

50.6

015

.30

07/

03/

89d

eliv

er b

ack

doo

r on

ly

1003

10/

12/

8910

4vi

a up

sn

B77

890

10/

13/

8935

.60

10.8

011

/04

/89

1004

04/

12/

8910

6ri

ng b

ell t

wic

ey

8006

04/

30/

8995

.80

19.2

0

1005

12/

04/

8911

6ca

ll be

fore

del

iver

ing

n28

6512

/19

/89

80.8

016

.20

12/

30/

89

1006

09/

19/

8911

2af

ter

10 a

my

Q13

557

70.8

014

.20

1007

03/

25/

8911

7n

2786

9304

/23

/89

125.

9025

.20

1008

11/

17/

8911

0cl

osed

Mon

day

yL

Z23

012

/06

/89

45.6

013

.80

12/

21/

89

1009

02/

14/

8911

1d

oor

next

to s

uper

save

rn

4745

03/

04/

8920

.40

10.0

004

/21

/89

1010

05/

29/

8911

5d

eliv

er 7

76 G

ary

n42

9Q06

/08

/89

40.6

012

.30

07/

22/

89if

no

answ

er

1011

03/

23/

8910

4up

sn

B77

897

04/

13/

8910

.40

5.00

06/

01/

89

1012

06/

05/

8911

7n

2787

0106

/09

/89

70.8

014

.20

1013

09/

01/

8910

4vi

a up

sn

B77

930

09/

18/

8960

.80

12.2

010

/10

/89

1014

05/

01/

8910

6ri

ng b

ell,

kick

doo

r lo

udly

n80

5205

/10

/89

40.6

012

.30

07/

18/

89

1015

07/

10/

8911

0cl

osed

Mon

nM

A00

308

/01

/89

20.6

06.

3008

/31

/89

A-12 Demonstration Database and Application

Page 641: Manual Informix

Data in the stores Database

stock Tablestock_num manu_code description unit_price unit unit_descr

1 HRO baseball gloves 250.00 case 10 gloves/case

1 HSK baseball gloves 800.00 case 10 gloves/case

1 SMT baseball gloves 450.00 case 10 gloves/case

2 HRO baseball 126.00 case 24/case

3 HSK baseball bat 240.00 case 12/case

4 HSK football 960.00 case 24/case

4 HRO football 480.00 case 24/case

5 NRG tennis racquet 28.00 each each

5 SMT tennis racquet 25.00 each each

5 ANZ tennis racquet 19.80 each each

6 SMT tennis ball 36.00 case 24 cans/case

6 ANZ tennis ball 48.00 case 24 cans/case

7 HRO basketball 600.00 case 24/case

8 ANZ volleyball 840.00 case 24/case

9 ANZ volleyball net 20.00 each each

manufact Table

manu_code manu_name

ANZ Anza

HSK Husky

HRO Hero

NRG Norge

SMT Smith

Demonstration Database and Application A-13

Page 642: Manual Informix

Data in the stores Database

state Table

code sname code sname

AK Alaska MT Montana

AL Alabama NB Nebraska

AR Arkansas NC North Carolina

AZ Arizona ND North Dakota

CA California NH New Hampshire

CO Colorado NJ New Jersey

CT Connecticut NM New Mexico

DE Delaware NV Nevada

FL Florida NY New York

GA Georgia OH Ohio

HI Hawaii OK Oklahoma

IA Iowa OR Oregon

ID Idaho PA Pennsylvania

IL Illinois RI Rhode Island

IN Indiana SC South Carolina

KS Kansas SD South Dakota

KY Kentucky TN Tennessee

LA Louisiana TX Texas

MA Massachusetts UT Utah

MD Maryland VA Virginia

ME Maine VT Vermont

MI Michigan WA Washington

MN Minnesota WI Wisconsin

MO Missouri WV West Virginia

MS Mississippi WY Wyoming

A-14 Demonstration Database and Application

Page 643: Manual Informix

The Demonstration Application

The Demonstration ApplicationThe following pages contain the form specifications, INFORMIX-4GL sourcecode modules, and help message source file for the demo4.4ge demonstra-tion application. The application is not complete, and some of the functionscalled by the menus are merely ‘‘dead ends.’’

File Name Descriptioncustform.per Form for displaying customer informationorderform.per Form for entering an orderstate_list.per Form for displaying a list of statesstock_sel.per Form for displaying a list of stock itemsd4_globals.4gl Module containing global definitionsd4_main.4gl Module containing MAIN routined4_cust.4gl Module handling the Customer optiond4_orders.4gl Module handling the Orders optiond4_stock.4gl Module handling the Stock optiond4_report.4gl Module handling the Report optiond4_demo.4gl Module handling hidden sample source code optionhelpdemo.src Source file for help messages

custform.per

DATABASE stores

SCREEN{

Customer Form

Number :[f000 ]Owner Name :[f001 ][f002 ]Company :[f003 ]Address :[f004 ]

[f005 ]City :[f006 ] State:[a0] Zipcode:[f007 ]Telephone :[f008 ]

}

TABLEScustomer

ATTRIBUTESf000 = 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";

Demonstration Database and Application A-15

Page 644: Manual Informix

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 ]==============================================================================

}

TABLEScustomer orders items stock

ATTRIBUTESf000 = 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 = orders.order_num;f010 = orders.order_date, DEFAULT = TODAY;f011 = orders.po_num;f012 = orders.ship_instruct;

f013 = items.item_num, NOENTRY;f014 = items.stock_num;a1 = items.manu_code, UPSHIFT;f015 = stock.description, NOENTRY;f016 = items.quantity;f017 = stock.unit_price, NOENTRY;f018 = items.total_price, NOENTRY;f019 = formonly.t_price TYPE MONEY;

INSTRUCTIONSSCREEN 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

Page 645: Manual Informix

The Demonstration Application

state_list.per

DATABASE stores

SCREEN{

State Selection

[a0] [f000 ][a0] [f000 ][a0] [f000 ][a0] [f000 ][a0] [f000 ][a0] [f000 ][a0] [f000 ]}

TABLESstate

ATTRIBUTESa0 = state.code;f000 = state.sname;

INSTRUCTIONSDELIMITERS " "SCREEN RECORD s_state[7](state.*)

stock_sel.per

DATABASE stores

SCREEN{

[f018][f019][f020 ][f021 ][f022 ][f023 ][f018][f019][f020 ][f021 ][f022 ][f023 ][f018][f019][f020 ][f021 ][f022 ][f023 ]

}

TABLESstock

ATTRIBUTESf018 = FORMONLY.stock_num;f019 = FORMONLY.manu_code;f020 = FORMONLY.manu_name;f021 = FORMONLY.description;f022 = FORMONLY.unit_price;f023 = FORMONLY.unit_descr;

INSTRUCTIONSDELIMITERS " "SCREEN RECORD s_stock[3] (FORMONLY.stock_num THRU FORMONLY.unit_descr)

Demonstration Database and Application A-17

Page 646: Manual Informix

The Demonstration Application

d4_globals.4gl

DATABASE stores

GLOBALSDEFINE

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

Page 647: Manual Informix

The Demonstration Application

d4_main.4gl

GLOBALS"d4_globals.4gl"

MAIN

DEFER INTERRUPTOPTIONSHELP 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 101CALL customer()CALL ring_menu()

COMMAND "Orders" "Enter and maintain orders" HELP 102CALL orders()CALL ring_menu()

COMMAND "Stock" "Enter and maintain stock list" HELP 103CALL stock()CALL ring_menu()

COMMAND "Reports" "Print reports and mailing labels" HELP 104CALL 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 105CLEAR SCREENEXIT PROGRAM

END MENUEND MAIN

FUNCTION bang()DEFINE cmd CHAR(80),

x CHAR(1)

CALL clear_menu()LET x = "!"WHILE x = "!"

PROMPT "!" FOR cmdRUN cmdPROMPT "Type RETURN to continue." FOR CHAR x

END WHILEEND FUNCTION

FUNCTION mess(str, mrow)DEFINE str CHAR(80),

Demonstration Database and Application A-19

Page 648: Manual Informix

The Demonstration Application

mrow SMALLINT

DISPLAY " ", str CLIPPED AT mrow,1SLEEP 3DISPLAY "" 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,1DISPLAY "" AT 2,1

END FUNCTION

FUNCTION get_states()

DECLARE c_state CURSOR FORSELECT * FROM stateORDER BY sname

LET state_cnt = 1FOREACH c_state INTO p_state[state_cnt].*

LET state_cnt = state_cnt + 1IF state_cnt > 50 THEN

EXIT FOREACHEND IF

END FOREACHLET state_cnt = state_cnt - 1

END FUNCTION

FUNCTION get_stocks()

DECLARE stock_list CURSOR FORSELECT stock_num, manufact.manu_code,

manu_name, description, unit_price, unit_descrFROM stock, manufactWHERE stock.manu_code = manufact.manu_codeORDER BY stock_num

LET stock_cnt = 1FOREACH stock_list INTO p_stock[stock_cnt].*

LET stock_cnt = stock_cnt + 1IF stock_cnt > 30 THEN

EXIT FOREACHEND IF

END FOREACHLET stock_cnt = stock_cnt - 1

END FUNCTION

A-20 Demonstration Database and Application

Page 649: Manual Informix

The Demonstration Application

d4_cust.4gl

GLOBALS"d4_globals.4gl"

FUNCTION customer()

OPTIONSFORM 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 = NULLMENU "CUSTOMER"

COMMAND "One-add" "Add a new customer to the database" HELP 201CALL add_customer(FALSE)

COMMAND "Many-add" "Add several new customer to database" HELP 202CALL add_customer(TRUE)

COMMAND "Find-cust" "Look up specific customer" HELP 203CALL 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 204CALL update_customer()NEXT OPTION "Find-cust"

COMMAND "Delete-cust" "Remove a customer from database" HELP 205CALL delete_customer()NEXT OPTION "Find-cust"

COMMAND "Exit" "Return to MAIN Menu" HELP 206CLEAR SCREENEXIT MENU

END MENUOPTIONS

FORM LINE 3END 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 WHILECALL mess("Multiple insert completed - current screen values ignored", 23)

ELSEIF input_cust() THEN

ERROR "Customer data entered" ATTRIBUTE (GREEN)ELSE

CLEAR FORMLET p_customer.customer_num = NULLERROR "Customer addition aborted" ATTRIBUTE (RED, REVERSE)

END IFEND IF

END FUNCTIONFUNCTION input_cust()

Demonstration Database and Application A-21

Page 650: Manual Informix

The Demonstration Application

DISPLAY "Press ESC to enter new customer data" AT 1,1INPUT BY NAME p_customer.*

AFTER FIELD stateCALL 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 = TRUEEXIT INPUT

END INPUTIF int_flag THEN

LET int_flag = FALSERETURN(FALSE)

END IFLET p_customer.customer_num = 0INSERT 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 FORMCALL clear_menu()

MESSAGE "Enter criteria for selection"CONSTRUCT where_part ON customer.* FROM customer.*MESSAGE ""IF int_flag THEN

LET int_flag = FALSECLEAR FORMERROR "Customer query aborted" ATTRIBUTE(RED, REVERSE)LET p_customer.customer_num = NULLRETURN (p_customer.customer_num)

END IFLET query_text = "select * from customer where ", where_part CLIPPED,

" order by lname"PREPARE statement_1 FROM query_textDECLARE customer_set SCROLL CURSOR FOR statement_1

A-22 Demonstration Database and Application

Page 651: Manual Informix

The Demonstration Application

OPEN customer_setFETCH FIRST customer_set INTO p_customer.*IF status = NOTFOUND THEN

LET exist = FALSEELSE

LET exist = TRUEDISPLAY 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 IFDISPLAY 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 IFDISPLAY 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 = TRUEEXIT MENU

COMMAND "Quit" "Quit BROWSE without selecting a customer"LET chosen = FALSEEXIT MENU

END MENUEND IFCLOSE customer_set

IF NOT exist THENCLEAR FORMCALL mess("No customer satisfies query", mrow)LET p_customer.customer_num = NULLRETURN (FALSE)

END IFIF NOT chosen THEN

CLEAR FORMLET p_customer.customer_num = NULLCALL mess("No selection made", mrow)RETURN (FALSE)

END IFRETURN (TRUE)

END FUNCTION

Demonstration Database and Application A-23

Page 652: Manual Informix

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 IFMESSAGE "Press F1 or CTRL-F for field-level help"DISPLAY "Press ESC to update customer data; DEL to abort" AT 1,1INPUT BY NAME p_customer.* WITHOUT DEFAULTS

AFTER FIELD stateCALL statehelp()DISPLAY "Press ESC to update customer data; DEL to abort", "" AT 1,1

ON KEY (F1, CONTROL-F)CALL customer_help()

END INPUTIF 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 = FALSESELECT * INTO p_customer.* FROM customer

WHERE customer_num = p_customer.customer_numDISPLAY BY NAME p_customer.*ERROR "Customer update aborted" ATTRIBUTE (RED, REVERSE)

END IFEND 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)

RETURNEND IF

SELECT COUNT(*) INTO num_ordersFROM ordersWHERE customer_num = p_customer.customer_num

IF num_orders THENERROR "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]" THENDELETE FROM customer

WHERE customer_num = p_customer.customer_numCLEAR FORMCALL mess("Customer entry deleted", 23)LET p_customer.customer_num = NULL

ELSEERROR "Deletion aborted" ATTRIBUTE (RED, REVERSE)

END IFEND FUNCTION

A-24 Demonstration Database and Application

Page 653: Manual Informix

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 CASEEND FUNCTION

FUNCTION statehelp()DEFINE idx INTEGER

SELECT COUNT(*) INTO idxFROM stateWHERE code = p_customer.state

IF idx = 1 THENRETURN

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,37WITH 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_stateLET p_customer.state = p_state[idx].codeDISPLAY BY NAME p_customer.state ATTRIBUTE (MAGENTA)RETURN

END FUNCTION

Demonstration Database and Application A-25

Page 654: Manual Informix

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 SCREENEXIT MENU

END MENUEND 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

RETURNEND IFIF NOT query_stat THEN

OPEN WINDOW cust_w AT 3,5WITH 19 ROWS, 72 COLUMNSATTRIBUTE(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_custCLOSE WINDOW cust_wIF p_customer.customer_num IS NULL THEN

RETURNELSE

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_instructIF int_flag THEN

LET int_flag = FALSECLEAR FORMERROR "Order input aborted" ATTRIBUTE (RED, REVERSE)RETURN

END IFINPUT ARRAY p_items FROM s_items.* HELP 311

A-26 Demonstration Database and Application

Page 655: Manual Informix

The Demonstration Application

BEFORE FIELD stock_numMESSAGE "Press ESC to write order"DISPLAY "Enter a stock number or press CTRL-B to scan stock list"

AT 1,1BEFORE FIELD manu_code

MESSAGE "Enter the code for a manufacturer"BEFORE FIELD quantity

DISPLAY "" AT 1,1MESSAGE "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_numDISPLAY p_items[pa_curr].manu_code TO s_items[s_curr].manu_codeDISPLAY p_items[pa_curr].description TO s_items[s_curr].descriptionDISPLAY p_items[pa_curr].unit_price TO s_items[s_curr].unit_priceNEXT FIELD quantity

END IFAFTER 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 NULLTHEN

CALL get_item()END IF

AFTER FIELD quantityMESSAGE ""LET pa_curr = arr_curr()IF p_items[pa_curr].unit_price IS NOT NULL

AND p_items[pa_curr].quantity IS NOT NULLTHEN

CALL item_total()ELSE

ERROR"A valid stock code, manufacturer, and quantity must all be entered"

ATTRIBUTE (RED, REVERSE)NEXT FIELD stock_num

END IFAFTER INSERT, DELETE

CALL renum_items()CALL order_total()

AFTER ROWCALL order_total()

END INPUT

IF int_flag THENLET int_flag = FALSECLEAR FORMERROR "Order input aborted" ATTRIBUTE (RED, REVERSE)RETURN

END IF

Demonstration Database and Application A-27

Page 656: Manual Informix

The Demonstration Application

WHENEVER ERROR CONTINUEBEGIN WORKINSERT 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 statu s < 0 THEN

ROLLBACK WORKERROR "Unable to complete update of orders table"

ATTRIBUTE(RED, REVERSE, BLINK)RETURN

END IFLET p_orders.order_num = SQLCA.SQLERRD[2]DISPLAY BY NAME p_orders.order_numIF NOT insert_items() THEN

ROLLBACK WORKERROR "Unable to insert items" ATTRIBUTE(RED, REVERSE, BLINK)RETURN

END IF

COMMIT WORKWHENEVER ERROR STOPCALL 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.00FOR i = 1 TO ARR_COUNT()

IF p_items[i].total_price IS NOT NULL THENLET order_total = order_total + p_items[i].total_price

END IFEND FORLET order_total = 1.1 * order_totalDISPLAY order_total TO t_price

ATTRIBUTE(GREEN)END FUNCTION

A-28 Demonstration Database and Application

Page 657: Manual Informix

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_priceDISPLAY 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

LET pa_curr = arr_curr()LET pa_total = arr_count()LET sc_curr = scr_line()LET sc_total = 4FOR k = pa_curr TO pa_total

LET p_items[k].item_num = kIF sc_curr <= sc_total THEN

DISPLAY k TO s_items[sc_curr].item_numLET sc_curr = sc_curr + 1

END IFEND FOR

END FUNCTION

FUNCTION insert_items()DEFINE idx INTEGER

FOR idx = 1 TO arr_count()IF p_items[idx].quantity != 0 THEN

INSERT INTO itemsVALUES (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 statu s < 0 THENRETURN (FALSE)

END IFEND IF

END FORRETURN (TRUE)

END FUNCTION

FUNCTION get_stock()DEFINE idx integer

OPEN WINDOW stock_w AT 7, 3WITH 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_wRETURN p_stock[idx].stock_num, p_stock[idx].manu_code,

p_stock[idx].description, p_stock[idx].unit_priceEND FUNCTION

Demonstration Database and Application A-29

Page 658: Manual Informix

The Demonstration Application

FUNCTION get_order()DEFINE idx, exist, chosen INTEGER,

answer CHAR(1)

CALL clear_menu()CLEAR FORMIF NOT query_customer(2) THEN

RETURNEND IFDECLARE order_list CURSOR FOR

SELECT order_num, order_date, po_num, ship_instructFROM ordersWHERE customer_num = p_customer.customer_num

LET exist = FALSELET chosen = FALSEFOREACH order_list INTO p_orders.*

LET exist = TRUECLEAR orders.*FOR idx = 1 TO 4

CLEAR s_items[idx].*END FORDISPLAY 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, stockWHERE order_num = p_orders.order_num

AND items.stock_num = stock.stock_numAND items.manu_code = stock.manu_code

ORDER BY item_numLET idx = 1

FOREACH item_list INTO p_items[idx].*LET idx = idx + 1IF idx > 10 THEN

ERROR "More than 10 items; only 10 items displayed"ATTRIBUTE (RED, REVERSE)

EXIT FOREACHEND IF

END FOREACHCALL 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 = FALSEEXIT FOREACH

END IFPROMPT " Enter ’y’ to select this order ",

"or RETURN to view next order: " FOR CHAR answerIF answer MATCHES "[yY]" THEN

LET chosen = TRUEEXIT FOREACH

END IFEND FOREACH

IF NOT exist THENERROR "No orders found for this customer" ATTRIBUTE (RED)

ELSEIF NOT chosen THEN

CLEAR FORMERROR "No order selected for this customer" ATTRIBUTE (RED)

END IF

A-30 Demonstration Database and Application

Page 659: Manual Informix

The Demonstration Application

END IFEND 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 stockWHERE stock.stock_num = p_items[pa_curr].stock_num

AND stock.manu_code = p_items[pa_curr].manu_codeIF status THEN

LET p_items[pa_curr].description = NULLLET p_items[pa_curr].unit_price = NULL

END IFDISPLAY p_items[pa_curr].description, p_items[pa_curr].unit_price

TO s_items[sc_curr].description, s_items[sc_curr].unit_priceIF 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 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,file_name CHAR(20),msg CHAR(40)

DECLARE invoice_data CURSOR FORSELECT 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 mWHERE

((o.order_num=p_orders.order_num) AND(i.order_num=p_orders.order_num) AND(i.stock_num=s.stock_num ANDi.manu_code=s.manu_code) AND(i.manu_code=m.manu_code))

ORDER BY 9

Demonstration Database and Application A-31

Page 660: Manual Informix

The Demonstration Application

CASE (print_option)WHEN "f"

START REPORT r_invoice TO file_nameCALL clear_menu()MESSAGE "Writing invoice -- please wait"

WHEN "p"START REPORT r_invoice TO PRINTERCALL clear_menu()MESSAGE "Writing invoice -- please wait"

WHEN "s"START REPORT r_invoice

END CASEFOREACH invoice_data INTO x_invoice.*

OUTPUT TO REPORT r_invoice (p_customer.*, x_invoice.*)END FOREACHFINISH REPORT r_invoiceIF print_option = "f" THEN

LET msg = "Invoice written to file ", file_name CLIPPEDCALL mess(msg, 23)

END IFEND FUNCTION

REPORT r_invoice (c, x)DEFINE c RECORD LIKE customer.*,

x RECORDorder_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)

OUTPUTLEFT MARGIN 0RIGHT MARGIN 0TOP MARGIN 1BOTTOM MARGIN 1PAGE LENGTH 48

A-32 Demonstration Database and Application

Page 661: Manual Informix

The Demonstration Application

FORMATBEFORE GROUP OF x.order_num

SKIP TO TOP OF PAGESKIP 1 LINEPRINT 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 LINESPRINT "Bill To:", COLUMN 10,c.fname CLIPPED, " ", c.lname CLIPPED;PRINT COLUMN 56,"Invoice No. ",x.order_num USING "&&&&&"PRINT COLUMN 10,c.companyPRINT COLUMN 10,c.address1 CLIPPED;PRINT COLUMN 56,"Invoice Date: ", x.order_datePRINT 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_numPRINT COLUMN 10,c.phone CLIPPED;PRINT COLUMN 56,"Backlog Status: ",x.backlogSKIP 1 LINESPRINT COLUMN 10,"Shipping Instructions: ", x.ship_instructPRINT COLUMN 10,"Ship Date: ",x.ship_date USING "ddd. mmm dd, yyyy";PRINT " Weight: ", x.ship_weight USING "#####&.&&"SKIP 1 LINESPRINT "----------------------------------------";PRINT "---------------------------------------"PRINT " Stock Unit ";PRINT " Item "PRINT " # Num Man Description Qty Cost Unit ";PRINT " Unit Description Total"SKIP 1 LINESLET calc_total = 0.00

ON EVERY ROWPRINT 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_numSKIP 1 LINESPRINT "----------------------------------------";PRINT "---------------------------------------"PRINT COLUMN 50, " Sub-total: ",calc_total USING "$$$$$$$&.&&"LET sales_tax = 0.065 * calc_totalLET x.ship_charge = 0.035 * calc_totalPRINT 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_taxPRINT 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

Page 662: Manual Informix

The Demonstration Application

d4_stock.4gl

GLOBALS"d4_globals.4gl"

FUNCTION stock()MENU "STOCK"

COMMAND "Add-stock" "Add new stock items to database" HELP 401CALL add_stock()

COMMAND "Find-stock" "Look up specific stock item" HELP 402CALL query_stock()

COMMAND "Update-stock" "Modify current stock information" HELP 403CALL update_stock()

COMMAND "Delete-stock" "Remove a stock item from database" HELP 404CALL delete_stock()

COMMAND "Exit" "Return to MAIN Menu" HELP 405CLEAR SCREENEXIT MENU

END MENUEND 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

Page 663: Manual Informix

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 SCREENCALL ring_menu()

COMMAND "Accounts-receivable" "Print current unpaid orders" HELP 502CALL print_ar()CLEAR SCREENCALL ring_menu()

COMMAND "Backlog" "Print backlogged orders" HELP 503CALL print_backlog()CLEAR SCREENCALL ring_menu()

COMMAND "Stock-list" "Print stock available" HELP 504CALL print_stock()CLEAR SCREENCALL ring_menu()

COMMAND "Options" "Change the report output options" HELP 505CALL update_options()CALL ring_menu()

COMMAND "Exit" "Return to MAIN Menu" HELP 506CLEAR SCREENEXIT MENU

END MENUEND FUNCTION

FUNCTION print_labels()DEFINE where_part CHAR(200),

query_text CHAR(250),msg CHAR(50),file_name CHAR(20)

OPTIONSFORM 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,1MESSAGE "Use query-by-example to select customer list"CONSTRUCT BY NAME where_part ON customer.*IF int_flag THEN

LET int_flag = FALSEERROR "Label print request aborted"RETURN

END IFMESSAGE ""LET query_text = "select * from customer where ", where_part CLIPPED,

" order by zipcode"PREPARE label_st FROM query_textDECLARE label_list CURSOR FOR label_stCASE (print_option)

Demonstration Database and Application A-35

Page 664: Manual Informix

The Demonstration Application

WHEN "f"PROMPT " Enter file name for labels >" FOR file_nameIF file_name IS NULL THEN

LET file_name = "labels.out"END IFMESSAGE "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_reportCLEAR SCREEN

END CASEFOREACH label_list INTO p_customer.*

OUTPUT TO REPORT labels_report (p_customer.*)IF int_flag THEN

LET int_flag = FALSEEXIT FOREACH

END IFEND FOREACHFINISH REPORT labels_reportIF int_flag THEN

LET int_flag = FALSE

ERROR "Label printing aborted" ATTRIBUTE (RED, REVERSE)RETURN

END IFIF print_option = "f" THEN

LET msg = "Labels printed to ", file_name CLIPPEDCALL mess(msg, 23)

END IFCLOSE FORM customerOPTIONS

FORM LINE 3END FUNCTION

REPORT labels_report (rl)DEFINE rl RECORD LIKE customer.*

OUTPUTTOP MARGIN 0BOTTOM MARGIN 0PAGE LENGTH 6

FORMATON EVERY ROWSKIP TO TOP OF PAGEPRINT rl.fname CLIPPED, 1 SPACE, rl.lnamePRINT rl.companyPRINT rl.address1

A-36 Demonstration Database and Application

Page 665: Manual Informix

The Demonstration Application

IF rl.address2 IS NOT NULL THENPRINT rl.address2

END IFPRINT rl.city CLIPPED, ", ", rl.state, 2 SPACES, rl.zipcodeIF print_option = "s" THEN

PAUSE "Type RETURN to continue"END IF

END REPORT

FUNCTION print_ar()DEFINE r RECORD

customer_num LIKE customer.customer_num,fname LIKE customer.fname,lname LIKE customer.lname,company LIKE customer.company,order_num LIKE orders.order_num,order_date LIKE orders.order_date,ship_date LIKE orders.ship_date,paid_date LIKE orders.paid_date,total_price LIKE items.total_price

END RECORD,file_name CHAR(20),msg CHAR(50)

DECLARE ar_list CURSOR FORSELECT customer.customer_num,fname,lname,company,

orders.order_num,order_date,ship_date,paid_date,total_price

FROM customer,orders,itemsWHERE customer.customer_num=orders.customer_num AND

paid_date IS NULL ANDorders.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_nameIF file_name IS NULL THEN

LET file_name = "ar.out"END IFMESSAGE "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_reportCLEAR SCREENMESSAGE "Printing AR REPORT -- Please wait"

END CASE

Demonstration Database and Application A-37

Page 666: Manual Informix

The Demonstration Application

FOREACH ar_list INTO r.*OUTPUT TO REPORT ar_report (r.*)IF int_flag THEN

LET int_flag = FALSEEXIT FOREACH

END IFEND FOREACHFINISH REPORT ar_reportIF int_flag THEN

LET int_flag = FALSEERROR "AR REPORT printing aborted" ATTRIBUTE (RED, REVERSE)RETURN

END IFIF print_option = "f" THEN

LET msg = "AR REPORT printed to ", file_name CLIPPEDCALL mess(msg, 23)

END IFEND FUNCTION

REPORT ar_report (r)DEFINE r RECORD

customer_num LIKE customer.customer_num,fname LIKE customer.fname,lname LIKE customer.lname,company LIKE customer.company,order_num LIKE orders.order_num,order_date LIKE orders.order_date,ship_date LIKE orders.ship_date,paid_date LIKE orders.paid_date,total_price LIKE items.total_price

END RECORD,name_text CHAR(80)

OUTPUTPAGE LENGTH 22LEFT MARGIN 0

FORMATPAGE HEADER

PRINT 15 SPACES,"West Coast Wholesalers, Inc."PRINT 6 SPACES,

"Statement of ACCOUNTS RECEIVABLE - ",TODAY USING "mmm dd, yyyy"

SKIP 1 LINESLET name_text = r.fname CLIPPED," ",r.lname CLIPPED,"/",

r.company CLIPPEDPRINT 29 - length(name_text)/2 SPACES, name_textSKIP 1 LINESPRINT " Order Date Order Number Ship Date Amount"PRINT "----------------------------------------------------------"

BEFORE GROUP OF r.customer_numSKIP TO TOP OF PAGE

AFTER GROUP OF r.order_numNEED 3 LINESPRINT " ",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_numPRINT 42 SPACES,"----------------"PRINT 42 SPACES,GROUP SUM(r.total_price) USING "$$$$,$$$,$$$.&&"

A-38 Demonstration Database and Application

Page 667: Manual Informix

The Demonstration Application

PAGE TRAILERIF 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,25LET po = " ", print_optionDISPLAY 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 MENUDISPLAY "" 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

Page 668: Manual Informix

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 SCREENEXIT MENU

END MENUEND FUNCTION

A-40 Demonstration Database and Application

Page 669: Manual Informix

The Demonstration Application

helpdemo.src

.101The Customer option presents you with a menu that allows you to:

o Add new customers to the databaseo Locate customers in the databaseo Update customer fileso Remove customers from the database

.102The Orders option presents you with a menu that allows you to:

o Enter a new order and print an invoiceo Update an existing ordero Look up and display orderso Remove orders from the database

.103The Stock option presents you with a menu that allows you to:

o Add new items to the list of stocko Look up and display stock itemso Modify current stock descriptions and valueso Remove items from the list of stock

.104The Reports option presents you with a menu that allows you to:

o Select and print mailing labels sorted by zip codeo Print a report of current accounts receivableo Print a report of backloged orderso Print a list of current stock availableo Change the report output options

.105The Exit option leaves the program and returns you to the operating system.

.201The 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 pressingthe function key F1 when the cursor is in the field. When you have enteredall the data you want for a given customer, press ESC to enter the data in thedatabase. If you want to abort a given entry and not write it to the database,press the INTERRUPT key (usually DEL or CTRL-C).

.202The Many-add option enables you to enter data on new customers to thedatabase. You may get assistance on what input is appropriate for each fieldby pressing the function key F1 when the cursor is in the field. When youhave entered all the data you want for a given customer, press ESC to enterthe data in the database. If you want to abort a given entry and not write itto the database, press the INTERRUPT key (usually DEL or CTRL-C). After eachentry, the cursor will move to the beginning of the form and await the entryof the next customer. If you have no more customers to add, press CTRL-Z toreturn to the CUSTOMER Menu.

Demonstration Database and Application A-41

Page 670: Manual Informix

The Demonstration Application

.203The Find-cust option allows you to select one or more customers and to displaytheir data on the screen by using query-by-example input. Use the RETURN orarrow keys to move through the form. Enter the criteria you want the programto use in searching for customers. Your options include:

o Literal valueso A range of values (separated by ":")o A list of values (separated by "|")o Relational operators (for example ">105")o Wildcards like ? and * to match single or any number of characters

.204The Update-cust option enables you to alter data on old customers in thedatabase. You must first select a current customer row to deal with by usingthe Find-cust option. You may get assistance on what input is appropriate foreach 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 toenter the data in the database. If you want to abort the changes and not writethem to the database, press the INTERRUPT key (usually DEL or CTRL-C).

.205The Delete-cust option enables you to remove customers from the database.You must first select a current customer row to deal with by using theFind-cust option. For your protection, you will be asked to confirmthat the record should be deleted. Once deleted, it cannot berestored. Customers with active orders can not be deleted.

.206The Exit option of the CUSTOMER Menu takes you back to the MAIN Menu.

.301The 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 selectioncriteria. You will then enter the order date, PO number, and shippinginstructions. The detail line items are then entered into a scrolling displayarray. Up to ten items may be entered using the four line screen array. Afterthe new order is entered, an invoice is automatically generated and displayedon the screen.

.302The Update-order option is currently not implemented.

.303The Find-order option enables you to browse through and select an existingorder. You must first select the desired customer (or customers) who’s ordersyou wish to scan. For each customer selected, each corresponding order willbe displayed on the screen for examination. You may either select an invoice,skip to the next invoice, or cancel processing.

.304The Delete-order option is currently not implemented.

.305The Exit option of the ORDER Menu returns you to the MAIN Menu.

A-42 Demonstration Database and Application

Page 671: Manual Informix

The Demonstration Application

.311You may enter up to ten line items into the scrolling screen array. A numberof standard functions are available for manipulating the cursor in a screenarray.

o F1 Insert new line in the screen arrayo F2 Remove the current line from the screen arrayo F3 Page down one page in the screen arrayo F4 Page up one page in the screen arrayo ESC Exit input arrayo CTRL-B When in the Stock Number or Manufacturer Code fields,

a window will open in the middle of the screen anddisplay a scrolled list of all items in stock, identifiedby the stock number and manufacturer. Using F3, F4, andthe up and down arrow keys, move the cursor to the linethat identifies the desired item and hit ESC. Thewindow will disappear and the selected information willautomatically appear in the proper line.

o etc... The arrow-keys, and the standard field editing keysare available

The item_total field will be displayed in reverse-video green for totalamounts over $500.

.401The Add-stock option is currently not implemented.

.402The Find-stock option is currently not implemented.

.403The Update-stock option is currently not implemented.

.404The Delete-stock option is currently not implemented.

.405The Exit option of the STOCK Menu returns you to the MAIN Menu.

.501The Labels option enables you to create a list of mailing labels generatedusing a query-by-example specification. You will be prompted for the outputfile name.

.502The Accounts-receivable option enables you to create a report summarizing allunpaid orders in the database. You will be prompted for the output file name.

.503The Backlog option is currently not implemented.

.504The Stock-list option is currently not implemented.

.505The Options option enables you to change the destination of any reportgenerated during the current session. The default option is to display allreports on the terminal screen. The other options are to print all reports toeither the printer or an operating system file.

.506The Exit option of the REPORT Menu returns you to the MAIN Menu.

Demonstration Database and Application A-43

Page 672: Manual Informix

The Demonstration Application

.1001The Number field on the Customer Form contains the serial integer assigned tothe customer row when the data for the customer is first entered into thedatabase. It is a unique number for each customer. The lowest value of thisfield is 101.

.1002The first section following the Name label should contain the first name of thecontact person at the customer’s company.

.1003The second section following the Name label should contain the last name of thecontact person at the customer’s company.

.1004This field should contain the name of the customer’s company.

.1005The first line of the Address section of the form should contain the mailingaddress of the company.

.1006The second line of the Address section of the form should be used only whenthere is not sufficient room in the first line to contain the entire mailingaddress.

.1007The City field should contain the city name portion of the mailing address ofthe customer.

.1008Enter the two-character code for the desired state. If no code is entered, orthe entered code is not in the program’s list of valid entries, a window willappear on the screen with a scrolling list of all states and codes. Using theF3, F4, up and down arrow keys, move the cursor to the line containing thedesired state. After typing ESC, the window will disappear and the selectedstate code will appear in the customer entry screen.

.1009Enter the five digit Zip Code in this field.

.1010Enter the telephone number of the contact person at the customer’s company.Include the Area Code and extension using the format "###-###-#### #####".

.2001The following is the INFORMIX-4GL source for the main menu. Note that onlythe text is specified by the MENU statement; the structure and runtime menufunctions are built-in.

OPTIONSHELP FILE "helpdemo"

OPEN FORM menu_form FROM "ring_menu"DISPLAY FORM menu_formMENU "MAIN"

COMMAND "Customer" "Enter and maintain customer data" HELP 101CALL customer()DISPLAY FORM menu_form

COMMAND "Orders" "Enter and maintain orders" HELP 102CALL orders()DISPLAY FORM menu_form

COMMAND "Stock" "Enter and maintain stock list" HELP 103CALL stock()DISPLAY FORM menu_form

A-44 Demonstration Database and Application

Page 673: Manual Informix

The Demonstration Application

COMMAND "Reports" "Print reports and mailing labels" HELP 104CALL reports()DISPLAY FORM menu_form

COMMAND "Exit" "Exit program and return to operating system" HELP 105CLEAR SCREENEXIT PROGRAM

END MENU

.2002The following is the INFORMIX-4GL source code for mailing-label selection andprinting. The CONSTRUCT statement manages the query-by-example input andbuilds 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_textDECLARE label_list CURSOR FOR mail_queryPROMPT "Enter file name for labels >" FOR file_nameMESSAGE "Printing mailing labels to ", file_name CLIPPED," -- Please wait"START REPORT labels_report TO file_nameFOREACH label_list INTO p_customer.*

OUTPUT TO REPORT labels_report (p_customer.*)END FOREACHFINISH REPORT labels_report

See the source code option REPORT for the corresponding report routine.

.2003The following is the INFORMIX-4GL source code for order entry using scrolledinput fields. Only the INPUT ARRAY statement in needed to utilize the fullscrolling features. Some additional code has been added merely to customizethe array processing to this application.

DISPLAY "Press ESC to write order" AT 1,1INPUT ARRAY p_items FROM s_items.* HELP 311

BEFORE FIELD stock_numMESSAGE "Enter a stock number."

BEFORE FIELD manu_codeMESSAGE "Enter the code for a manufacturer."

AFTER FIELD stock_num, manu_codeLET pa = arr_curr()LET sc = scr_line()SELECT description, unit_price

INTO p_items[pa].description,p_items[pa].unit_price

FROM stockWHERE stock_num = p_items[pa].stock_num AND

stock_manu = p_items[pa].menu_codeDISPLAY p_items[pa].description, p_items[pa].unit_price

TO stock[sc].*CALL item_total()

AFTER FIELD quantityCALL item_total()

AFTER INSERT, DELETE, ROWCALL order_total()

END INPUT

See the source code option QUERY-LANGUAGE for the SQL statements thatinsert the order information into the database.

Demonstration Database and Application A-45

Page 674: Manual Informix

The Demonstration Application

.2004The following is the INFORMIX-4GL source code that uses SQL to insert theentered order information into the database. Note that the use oftransactions ensures that database integrity is maintained, even if anintermediate operation fails.

BEGIN WORKLET p_orders.order_num = 0INSERT INTO orders VALUES (p_orders.*)IF statu s < 0 THEN

ROLLBACK WORKMESSAGE "Unable to complete update of orders table"RETURN

END IFLET p_orders.order_num = SQLCA.SQLERRD[2]DISPLAY BY NAME p_orders.order_numFOR i = 1 to arr_count()

INSERT INTO itemsVALUES (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 statu s < 0 THENROLLBACK WORKMessage "Unable to insert items"RETURN FALSE

END IFEND FORCOMMIT WORK

.2005The following is the INFORMIX-4GL source code that generates the mailing-labelreport. See the source code option CONSTRUCT for the report calling sequence.

REPORT labels_report (rl)DEFINE rl RECORD LIKE customer.*OUTPUT

TOP MARGIN 0PAGE LENGTH 6

FORMATON EVERY ROW

SKIP TO TOP OF PAGEPRINT rl.fname CLIPPED, 1 SPACE, rl.lnamePRINT rl.companyPRINT rl.address1IF rl.address2 IS NOT NULL THEN

PRINT rl.address2END IFPRINT rl.city CLIPPED, ", ", rl.state, 2 SPACES, rl.zipcode

END REPORT

.2006The following is the INFORMIX-4GL source code that manages a simple formfor data entry. Note the use of special key definitions during data entry.

OPEN FORM cust_form FROM "customer"DISPLAY FORM cust_formMESSAGE "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 stateCALL statehelp()

ON KEY (F1, CONTROL-F)

A-46 Demonstration Database and Application

Page 675: Manual Informix

The Demonstration Application

CALL customer_help()ON KEY (F2, CONTROL-Z)

CLEAR FORMRETURN

END INPUT

.2007The following is the INFORMIX-4GL source code that opens a window in thecustomer entry screen, displays the list of valid state names and codes, savesthe index into the p_state array for the selected state, closes the window, andreturns the index to the calling routine.

OPEN WINDOW w_state AT 8,40WITH 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_stateRETURN (idx)

.2008The following is the INFORMIX-4GL source code that allows the user to browsethrough the rows returned by a "scroll" cursor.

DECLARE customer_set SCROLL CURSOR FORSELECT * FROM customer

ORDER BY lnameOPEN customer_setFETCH FIRST customer_set INTO p_customer.*IF status = NOTFOUND THEN

LET exist = FALSEELSE

LET exist = TRUEDISPLAY 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 IFDISPLAY 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 IFDISPLAY 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

Page 676: Manual Informix

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 = TRUEEXIT MENU

COMMAND "Quit" "Quit BROWSE without selecting a customer"LET chosen = FALSEEXIT MENU

END MENUEND IFCLOSE customer_set

A-48 Demonstration Database and Application

Page 677: Manual Informix

Appendix

B

System CatalogsInformation about the database is maintained in the systemcatalogs. The system catalogs are as follows:

systables describes database tables.syscolumns describes columns in tables.sysindexes describes indexes on columns.systabauth identifies table-level privileges.syscolauth identifies column-level privileges.sysdepend describes how views depend on tables.syssynonyms lists synonyms for tables.sysusers identifies database-level privileges.sysviews defines views.sysconstraints records constraints placed on database

tables.syssyntable used for mapping of synonyms.

The following list gives a brief description of the systemcatalogs.

Page 678: Manual Informix

The SYSTABLES Catalog

The SYSTABLES CatalogColumnName Type Explanationtabname char(18) name of tableowner char(8) owner of tabledirpath char(64) directory path for the table filetabid serial internal table identifierrowsize smallint row sizencols smallint number of columnsnindexes smallint number of indexesnrows integer number of rowscreated date date createdversion integer table version numbertabtype char(1) table type (T = table, V = view, S = synonym)audpath char(64) audit filename (full pathname)

IndexName Type Columnstabname unique tabname, ownertabid unique tabid

The SYSCOLUMNS CatalogColumnName Type Explanationcolname char(18) column nametabid integer table identifiercolno smallint column numbercoltype smallint column typecollength smallint column length (physical)

IndexName Type Columnscolumn unique tabid, colno

B-2 System Catalogs

Page 679: Manual Informix

The SYSINDEXES Catalog

The SYSINDEXES CatalogColumnName Type Explanationidxname char(18) index nameowner char(8) owner of indextabid integer table identifieridxtype char(1) index type (U = unique, D = dupls)clustered char(1) clusteringpart1 smallint column numberpart2 smallint column numberpart3 smallint column numberpart4 smallint column numberpart5 smallint column numberpart6 smallint column numberpart7 smallint column numberpart8 smallint column number

IndexName Type Columnsidxtab dupls tabididxname unique idxname, tabid

The SYSTABAUTH CatalogColumnName Type Explanationgrantor char(8) grantor of permissiongrantee char(8) grantee (receiver) of permissiontabid integer table identifiertabauth char(7) authorization type

IndexName Type Columnstabgtor unique tabid, grantor, granteetabgtee dupls tabid, grantee

The SYSCOLAUTH CatalogColumnName Type Explanationgrantor char(8) grantor of permissiongrantee char(8) grantee (receiver) of permissiontabid integer table identifiercolno smallint column numbercolauth char(2) authorization type

System Catalogs B-3

Page 680: Manual Informix

The SYSDEPEND Catalog

IndexName Type Columnscolgtor unique tabid, grantor, grantee, colnocolgtee dupls tabid, grantee

The SYSDEPEND CatalogColumnName Type Explanationbtabid integer tabid of base table or viewbtype char(1) base object type (table or view)dtabid integer tabid of dependent tabledtype char(1) dependent object type (only view now)

IndexName Type Columnsbtabid dupls btabiddtabid dupls dtabid

The SYSSYNONYMS CatalogColumnName Type Explanationowner char(8) user name of ownersynonym char(18) synonym identifiercreated date date synonym createdtabid integer table identifier

IndexName Type Columnssynonym unique owner, synonymsyntabid dupls tabid

The SYSUSERS CatalogColumnName Type Explanationusername char(8) user login identifierusertype char(1) D = DBA, R = RESOURCE, C = CONNECTpriority smallint reserved for future usepassword char(8) reserved for future use

IndexName Type Columnsusers unique username

B-4 System Catalogs

Page 681: Manual Informix

The SYSVIEWS Catalog

The SYSVIEWS CatalogColumnName Type Explanationtabid integer table identifierseqno smallint sequence numberviewtext char(64) portion of SELECT statement

IndexName Type Columnsview unique tabid, seqno

The SYSCONSTRAINTS CatalogColumnName Type Explanationconstrid serial reserved for future useconstrname char(18) constraint identifierowner char(8) user name of ownertabid integer table identifierconstrtype char(1) reserved for future useidxname char(18) index name

IndexName Type Columnsconstrname unique constrname, ownerconstrtabid dupls tabidconstrid unique constrid

The SYSSYNTABLE CatalogColumnName Type Explanationtabid integer table identifierturboname used on INFORMIX-OnLine onlydbname used on INFORMIX-OnLine onlytabname used on INFORMIX-OnLine onlyowner used on INFORMIX-OnLine onlybtabid integer tabid of base table or view

IndexName Type Columnssynntabid unique tabidsynnbtabid dupls btabid

System Catalogs B-5

Page 682: Manual Informix

The SYSSYNTABLE Catalog

B-6 System Catalogs

Page 683: Manual Informix

Appendix

C

EnvironmentVariablesINFORMIX-4GL makes the following assumptions aboutthe user’s environment:

• The editor used is the predominant operating systemeditor (usually vi).

• 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 arelocated in /usr/informix.

Page 684: Manual Informix

Setting Environment Variables

Setting Environment VariablesYou can change any of the assumptions by setting one or more of the environ-ment 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 thesystem prompt, you will have to assign it again the next time you log onto thesystem. 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 setthe ABCD environment variable to value:

ABCD=valueexport ABCD

If you are using the C shell, enter the following command to set the ABCDenvironment variable to value:

setenv ABCD value

INFORMIX-4GL recognizes the following environment variables:

DBANSIWARNDBANSIWARN specifies that you want to initiate Informix extension check-ing. Setting the DBANSIWARN environment variable before you compile a4GL program is functionally equivalent to compiling with the -ansi flag.When Informix extensions to ANSI standard syntax are encountered in yourprogram, warning messages are written to a .err file. At run time, the DBAN-SIWARN environment variable causes SQLAWARN[6] to be set to W when anon-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 envi-ronment as follows:

C shell:

setenv DBANSIWARN

Bourne shell:

DBANSIWARN=export DBANSIWARN

C-2 Environment Variables

Page 685: Manual Informix

DBDELIMITER

Once you have set DBANSIWARN, Informix extension checking is automaticuntil you logout or unset DBANSIWARN.

When you want to turn off Informix extension checking, you can unset theDBANSIWARN environment variable using the following commands.

C shell:

unsetenv DBANSIWARN

Bourne shell:

unset DBANSIWARN

DBDELIMITERDBDELIMITER specifies the field delimiter used by the dbload utility inunloaded 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 +

DBDATEDBDATE specifies the format you want to use for DATE values. ThroughDBDATE, 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 four-digit year, and the separator is a (/) slash (mm/dd/yyyy).

Other acceptable values for the separator are a hyphen ( - ), a period ( . ), or azero ( 0 ). (You use the zero to indicate no separator.) The slash appears if youattempt to use a value other than the hyphen, period, or zero to indicate theseparator, or if you do not include a separator character in the DBDATEdefinition.

Environment Variables C-3

Page 686: Manual Informix

DBEDIT

The separator value must always be specified last. The number of digits spec-ified for the year must always follow the Y. To make the date appear asmmddyy (with no separator), you would set the DBDATE environment vari-able for the C shell as follows:

setenv DBDATE MDY20

For the Bourne shell, you would use

DBDATE=MDY20export DBDATE

Suppose that you wanted the date to appear in European format(dd-mm-yyyy). For the C shell, you would set the DBDATE environmentvariable as follows:

setenv DBDATE DMY4-

For the Bourne shell, you would use

DBDATE=DMY4-export DBDATE

DBEDITDBEDIT names the text editor for creating program files, form specificationfiles, and command files from within the INFORMIX-4GL Programmer’sEnvironment. For most systems, the default is vi.

DBLANGDBLANG specifies the subdirectory of $INFORMIXDIR that containsthe message (.iem) files used by your program. The default is$INFORMIXDIR/msg.

C-4 Environment Variables

Page 687: Manual Informix

DBMONEY

If you want to use a message directory other than $INFORMIXDIR/msg, per-form the following steps:

1. Use the mkdir command to create the appropriate subdirectory in$INFORMIXDIR. Set the user and group to informix and the accesspermission for this directory to 755.

2. Set the DBLANG environment variable to the new subdirectory. (Specifyonly the name of the subdirectory and not the full pathname of thesubdirectory.) If you are using the Bourne shell, enter

DBLANG=dirnameexport 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 groupinformix and 644 access permission.

4. Run your program.

DBMONEYDBMONEY applies to MONEY values. It has the format

[ front ] { . | , } [ back ]

where front is the optional symbol that precedes the MONEY value, thecomma or the period is the optional symbol that separates the integral fromthe fractional part of the MONEY value, and back is the optional symbol thatfollows the MONEY value. The front and back symbols can be up to sevencharacters 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 (.) separatesthe integral from the fractional part of the MONEY value. (No back symbolappears.)

Suppose you wanted to represent MONEY values in deutsche marks. For theC shell, you would set the DBMONEY environment variable as follows:

setenv DBMONEY DM,

Environment Variables C-5

Page 688: Manual Informix

DBPATH

For the Bourne shell, you would use

DBMONEY=DM,export DBMONEY

where DM is the currency symbol, and the comma separates the integral fromthe fractional part of the MONEY value.

If you have specified both symbols and you make a change to either one, youmust respecify the other symbol and the value separator (comma or period).Similarly, if you change the value separator from a comma to a period, youmust respecify the front symbol as well as the back symbol (if you had previ-ously specified a back symbol).

DBPATHDBPATH specifies a list of directories (in addition to the current directory) forINFORMIX-4GL to search for databases and associated files. If you have notselected a database, INFORMIX-4GL looks to DBPATH as well as the currentdirectory to determine the list of available databases.

Once you have selected a database, INFORMIX-4GL looks first in the currentdirectory and then in the parent directory of the directory containing thedatabase (recall that each database is contained in a separate directory) forthe associated forms, reports, and command files.

For example, if you want INFORMIX-4GL to search for database files inKevin’s and Zooie’s directories, as well as in your current directory, youwould specify

DBPATH=/usr/Kevin:/usr/Zooieexport DBPATH

Make sure you enter a colon between the directory names.

DBPRINTDBPRINT specifies the print program for your computer. For most UNIX sys-tems, the default program is lp.

DBTEMPDBTEMP specifies the directory into which INFORMIX-4GL should place itstemporary files. The default is the /tmp directory.

C-6 Environment Variables

Page 689: Manual Informix

INFORMIXDIR

INFORMIXDIRINFORMIXDIR specifies the directory containing the INFORMIX-4GL files. Thedefault is the /usr/informix directory.

INFORMIXTERMINFORMIXTERM specifies whether INFORMIX-4GL should use the termcap orterminfo files to locate terminal capability information. If you do not setINFORMIXTERM, INFORMIX-4GL uses termcap.

If you are using the Bourne shell, enter:

INFORMIXTERM=typeexport INFORMIXTERM

where type is termcap or terminfo.

If you are using the C shell, enter:

setenv INFORMIXTERM= type

SQLEXECSQLEXEC is needed only if you have both INFORMIX-SE and INFOR-MIX-OnLine installed on your system, and you want to access INFORMIX-SE.If you have both engines installed, but you do not specify SQLEXEC, thenINFORMIX-OnLine is the default engine.

SQLEXEC must contain the full pathname of the database engine, which islocated in the lib subdirectory of $INFORMIXDIR.

To use INFORMIX-OnLine with the Bourne shell, specify:

SQLEXEC=$INFORMIXDIR/lib/sqlturboexport SQLEXEC

To use INFORMIX-SE with the Bourne shell, specify:

set SQLEXEC=$INFORMIXDIR/lib/sqlexecexport 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

Page 690: Manual Informix

SQLEXEC

C-8 Environment Variables

Page 691: Manual Informix

Appendix

D

Reserved WordsThis appendix contains a list of Informix reserved words.Do not use these words as identifiers or as program vari-able or host variable names. If you use reserved words asidentifiers or variables, your program (or SQL statement)may fail with an error.

This list contains reserved words from all Informix prod-ucts, although not all are reserved in each product. Notethat, while their use is not recommended, some reservedwords may not cause errors in every case. For example,words that are reserved in INFORMIX-4GL will not generatean error if used with only INFORMIX-SQL. However, ifyour INFORMIX-SQL application is later ported to anINFORMIX-4GL environment, any INFORMIX-4GLreserved words will cause errors. Additionally, some wordsonly generate errors if used as host or program variables,while other words only generate errors if used as identifi-ers.

In addition to the words on this list, you should not use C,ADA, or COBOL language keywords in your programs.

Page 692: Manual Informix

D-2 Reserved Words

abortabsoluteacceptaccessaddafterallallowingalterandansianyarrayasascascendingasciiatattributeattributesauditautoautonextaverageavgbackgroundbeforebeginbeginningbellbetweenblackblanksblinkblueboldborderbottombufferedbybytecallcase

charcharactercheckclearclippedcloseclustercolcolorcolorscolumncolumnscommandcommentcommentscommitcommittedcompositescompressconnectconstantconstraintconstructcontinueconvertcountcreatecurrentcursorcyandatabasedatedatetimedate_typedaydbadebugdecdecimaldecimal_typedeclaredec_tdefault

defaultsdeferdefinedeletedelimiterdelimitersdescdescendingdescribedescriptordimdirtydisplaydisplayonlydistinctdodominantdoubledowndownshiftdropdtimedtime_teco-*editaddeditupdateelseendend-execendifendingerrorescapeeveryexclusiveexecexecuteexistsexitexitnowexitsexplainextend

extentexternexternalfalsefetchfieldfilefinishfirstfixcharfloatflushforforeachformformatformonlyfoundfractionfreefromfunctionglobalsgogo togotograntgreengrouphavingheaderheadingshelpholdhouridentifiedififdefifndefimmediateinincludeindex

Page 693: Manual Informix

indicatorinfieldinfoinitializeinputinsertinstructionsintintegerinterruptintersectintervalintointrvl_tinverseinvisibleisisamisolationjoinjoiningkeylabellastleftlenlengthletlikelinelinenolinesloadlocatorlockloc_tloglonglong_floatlong_integerlookuploopmagenta

mainmarginmastermatchesmaxmdymemorymenumessageminminusminutemodmodemodifymodulemoneymonthnamenaturalneednewnextnextfieldnonocrnoentrynormalnotnot foundnotfoundnoupdatenownullnumericofoffonopenoptionoptionsororder

otherwiseoutouteroutputpackagepagepagenoparampausepercentperformpicturepipepositiveprecisionpreparepreviousprintprinterpriorprivilegeprivilegesprogrampromptpublicputqueryqueryclearquitraiserangereadreadonlyrealrecordrecoverredregisterrelativeremoverenamerepairrepeatable

reportrequiredresourcereturnreturningreverserevokerightrollbackrollforwardrowrowidrowsrunsavepointscreenscrollsecondsectionselectserialserial_typesetshareshiftshortshort_floatshort_integersitenamesizeskipsleepsmallfloatsmallintsomespacespacessqlsql*sqlcasqlchar_typesqldasqldecimal_type

Appendix D: Reserved Words 3

Page 694: Manual Informix

D-4 Reserved Words

sqlerrsqlerrorsqlfloat_typesqlint_typesqlmoney_typesqlsmfloat_typesqlsmint_typesqlwarningstabilitystartstartlogstaticstatisticsstatusstdvstepstopstringstructsubtract

subtypesumsynonymsystablestabletemptextthenthroughthrutimetiny_integertotodaytoptotaltrailertrailingtruetype

typedefundefunderlineunionuniqueunitsunloadunlockupupdateupshiftuserusingvalidatevaluesvarcharvariablevc_tverifyview

waitwaitingwarningweekdaywhenwheneverwherewhilewhitewindowwithwithoutwordwrapworkwrapyearyellowyeszerofill

Page 695: Manual Informix

Appendix

E

INFORMIX-4GLUtility ProgramsThis appendix describes nine utility programs that areincluded with the INFORMIX-4GL software. You can invokethese utilities at the system prompt to perform any of thefollowing tasks:

• The bcheck utility checks and restores the integrity ofyour index files.

• The dbload utility allows you to load data from otherdatabase systems or from raw data files into INFOR-MIX-4GL databases.

• The dbexport utility allows you to unload a databaseinto ASCII files.

• The dbimport utility allows you to create a databasefrom appropriate ASCII files.

• The dbschema utility allows you to output the SQLstatements necessary to replicate an individual table oran entire database.

• The dbupdate utility updates an SQL Version 1 databaseto an SQL Version 2 database.

• The mkmessage utility compiles programmer-definedhelp messages for INFORMIX-4GL applications.

• The sqlconv utility converts an INFORMIX database toan SQL-compatible database.

• The upscol utility enables you to establish defaultattributes for display fields that are linked to databasecolumns in your screen forms. It can also establish ini-tial default values for program variables and screenfields that you associate with columns of tables in yourdatabase.

Page 696: Manual Informix

The bcheck Utility

The bcheck UtilityFor every database table, INFORMIX-4GL creates two files in the databasedirectory. These files have names consisting of a few characters of the tablename, a unique number (starting at 100), and a filename extension. The exten-sion .dat identifes the data file, while the extension .idx identifies the indexfile. In the stores database, for instance, data in the customer table is storedin a file named custome100.dat, while a file named custome100.idx containsthe table indexes. To identify the actual filenames that INFORMIX-4GL hasassigned on your system, you can examine the stores.dbs directory, whereboth files reside.

Should these files be damaged, you may experience symptoms ranging fromsluggish performance to seemingly missing data. The bcheck utility, sup-plied with INFORMIX-4GL on INFORMIX-SE, can verify the integrity of bothfiles and repair and rebuild corrupted indexes. If you have used INFOR-MIX-4GL only as described in your manual and have not intentionally mod-ified these files in some other way, any damage is normally due either topower 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 twoare consistent. If they are not, bcheck asks whether you want each damagedindex to be deleted and rebuilt. For each index, bcheck prints a group of upto eight numbers. These numbers indicate the position of the key in eachrecord.

In running bcheck, you must specify the table name as it exists in the data-base directory (custome100, for example, instead of customer). The followingexample runs bcheck, with the -n option, on the customer table.

bcheck -n custome100

E-2 INFORMIX-4GL Utility Programs

Page 697: Manual Informix

The bcheck Utility

In the example on the next page of output from this command line, bcheckfinds no errors.

BCHECK C-ISAM B-tree Checker version 4.00.00Copyright (C) 1981-1989 Informix Software, Inc.Software Serial Number INF#R000000

C-ISAM File: custome100

Checking dictionary and file sizes.Index file node size = 1024Current C_ISAM index file node size = 1024Checking data file records.Checking indexes and key descriptions.Inde x 1 = unique key

0 index node(s) used -- 1 index b-tree level(s) usedInde x 2 = unique key (0,4,2)

1 index node(s) used -- 1 index b-tree level(s) usedInde x 3 = duplicates (111,5,0)

1 index node(s) used -- 1 index b-tree level(s) usedChecking 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 Check index file only

-l List entries in B+ trees

-n Answer no to all questions

-y Answer yes to all questions

-q Suppress printing of the program banner

-s 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 torespond to each error that it finds.

Use the -y option with caution. Do not run bcheck using the -y option if youare checking the files for the first time.

INFORMIX-4GL Utility Programs E-3

Page 698: Manual Informix

The bcheck Utility

Here is an example of bcheck output in which bcheck finds errors. The -noption is selected, so that each question bcheck asks is automaticallyanswered ‘‘no.’’

BCHECK C-ISAM B-tree Checker version 4.00.00Copyright (C) 1981-1989 Informix Software, Inc.Software Serial Number INF#R000000

C-ISAM File: custome100

Checking dictionary and file sizes.Index file node size = 1024Current C_ISAM index file node size = 1024Checking data file records.Checking indexes and key descriptions.Inde x 1 = unique key

0 index node(s) used -- 1 index b-tree level(s) used

ERROR: 3 bad data record(s)Delete index ? no

Inde x 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

Inde x 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 corruptedindexes.

E-4 INFORMIX-4GL Utility Programs

Page 699: Manual Informix

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.00Copyright (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.Inde x 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 ? yesInde x 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

Inde x 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 data record free listRecreate index 3Recreate index 2Recreate 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

Page 700: Manual Informix

The dbexport Utility

The dbexport Utility

OverviewUse dbexport to unload a database into ASCII files for import into anotherdatabase environment.

Syntaxdbexport [ -c ] [ -q ] database

[ -o directory-path | -t device -b blksize -s tapesize [ -f pathname ] ]

Explanationdbexport is the program name.

-c tells the program to continue even though errors occur.

-q tells the program not to display anything on its standardoutput.

database is the name of the database to be exported.

-o directory-path directs the output to a specified directory on disk.

-t device directs the output to a specified tape device.

-b blksize specifies the tape block size in kilobytes.

-s tapesize specifies the capacity of one tape reel.

-f pathname tells the program to write data definition statements to thefile pathname and not to the tape.

Notes1. 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 exclusivelock cannot be obtained, the program ends with a diagnostic message.

3. The dbexport program always creates a file of messages calleddbexport.out. This file contains any error messages and warnings, and italso contains a display of the SQL data definition statements that it is gen-erating. The same material is also written to the standard output unlessyou specify the -q option.

E-6 INFORMIX-4GL Utility Programs

Page 701: Manual Informix

The dbexport Utility

4. You can cancel the program with an Interrupt signal. The dbexport pro-gram 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 atape drive; otherwise, dbexport writes the files to disk. When you includethe -t option, you must also specify the tape device, the block size, and thevolume capacity.

6. When you include the -t option, the file of data definition statements andother commands (used by the dbimport utility) are ordinarily also writ-ten to the tape. Use the -f option to instruct the program to write these tothe 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 directorywith the name database.exp. This directory must not exist; the programwill create it. Its group will be informix. If you include the -o directory-path 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 statementsand other commands to dbimport is written to the file database.sql in thedatabase.exp directory.

ExamplesThe following command exports the stores database to tape with a block sizeof 16 kilobytes and a tape capacity of 24,000 kilobytes. The file of data defini-tion statements and other directions to dbimport is written to stores.imp inthe /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 INFORMIX-OnLine Programmer’s Manual for more information.

INFORMIX-4GL Utility Programs E-7

Page 702: Manual Informix

The dbimport Utility

The dbimport Utility

OverviewUse dbimport to create a database from ASCII files.

Syntaxdbimport [-c] [-q] database

[-i directory-path |-t device -b blksize -s tapesize [-f pathname] ][-d dbspace] [-l [ logpath | buffered] ] [-ansi]

Explanation-c tells the program to continue even when errors occur, unless

it is a fatal error.

-q tells the program not to display anything on its standardoutput.

database is the name of the database to import.

-i directory-path specifies the path to an input directory.

-t device specifies input from a particular tape device.

-b blksize specifies the tape block size in Kbytes.

-s tapesize specifies the capacity of one tape reel.

-f pathname tells the program to read data definition statements from thefile pathname and not from the tape.

-d dbspace when importing to INFORMIX-OnLine only, specifies thedbspace where the new database is to go.

-l specifies that the imported database is to use transactionlogging.

logpath when importing to the standard database engine only, spec-ifies the pathname of the transaction log file.

buffered when importing to INFORMIX-OnLine only, specifies buff-ered or unbuffered logging (unbuffered is the default).

-ansi tells the program to create the new database as MODE ANSI.

E-8 INFORMIX-4GL Utility Programs

Page 703: Manual Informix

The dbimport Utility

Notes1. The program always creates a message file called dbimport.out in the

current directory. This file contains messages and warnings related to therunning of the program. The message are also written to the standard out-put (normally the terminal screen) unless you include the -q option.

2. You can cancel the program with an interrupt signal. You are promptedfor confirmation before the program terminates.

3. The individual who runs dbimport is granted DBA privilege on the newdatabase.

4. When importing a database that uses the standard database engine, data-base files are created in the current directory.

5. Use the -l option to establish transaction logging for the imported data-base. This option is equivalent to the WITH LOG IN clause of the CREATEDATABASE statement. A database created as MODE ANSI requires trans-action logging. In this situation, you must include the -l option.

6. The dbimport utility reads multiple files containing database data fromeither disk or tape. Use the -t option to specify the source as tape; thedefault is disk. When you include the -t option, you must also specify thetape device, blocksize and volume capacity.

7. When you include the -t option, dbimport reads the data definitionstatements and other dbimport commands from the tape. Use the-f pathname option to instruct the program to read the database.sql file inpathname (instead of the tape) for the data definition statements and othercommands.

To use the -f option you must have also used it when you executed thedbexport program.

8. If you do not specify the -t option, the source of the database data is a diskdirectory with the name database.exp. The dbimport program looks forthis directory in the current working directory, or on the path specifiedwith the -i option. In either case, the program takes data definition andother commands from the file database.sql in the directory database.exp.(This is why the name database must be the same as was given todbexport.)

INFORMIX-4GL Utility Programs E-9

Page 704: Manual Informix

The dbimport Utility

ExampleThe following command imports the stores database from a tape with ablocksize of 16 Kbytes and capacity of 24,000 Kbytes. The file of data defini-tion 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 filestores.sql in that directory. The new database is created as MODE ANSI anduses logging.

dbimport -c stores -i /usr/informix/port -ansi -l /usr/work/stores.log

INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

E-10 INFORMIX-4GL Utility Programs

Page 705: Manual Informix

The dbload Utility

The dbload UtilityThe dbload utility provides a method for transferring data from ASCII filesinto an existing database. This program supports the easy and efficient trans-fer of database files created for other Informix products, or even for entirelydifferent database management systems. The dbload utility includes the fol-lowing features:

• Data from selected fields of one or more input files can be loaded intoselected 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 youspecify).

• 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 isreached on the number of records that cannot be entered into the databasebecause of errors.

• If your database supports transactions, you have the option of terminat-ing the loading process without committing any data from the batch ofrecords that exceeded your error limit.

To use dbload, you must have at least one ASCII input file of data records toenter, and at least one table to receive the data. You must then create acommand file to specify instructions for reading and loading the data. Finally,you must invoke dbload by entering an appropriate command line. The fol-lowing sections provide details about these procedures.

Input Files for the dbload UtilityJust as database tables store data in columns within rows, input file data mustbe arranged in fields within records. You must be able to specify a one-to-onecorrespondence between fields of the input records and columns of the newrows that dbload will insert in the database.

Data files for dbload must be ‘‘flat’’ ASCII files, containing only printablecharacters. The records containing the data to be transferred must be sepa-rated 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

Page 706: Manual Informix

The dbload Utility

Fixed-Length and Variable-Length Records

The record length can be either fixed or variable. An input file has fixed-lengthrecords if the locations of data fields and the number of characters are thesame across all records. If a file has variable-length records, every field mustend with the same delimiter character (which must not occur as data withinany field). This character does not need to be the same one that the DBDELIM-ITER 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 fileto 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 indata fields for MONEY columns.

Values of type DATE must be in mm / dd / yyyy format. Data for DATETIMEand INTERVAL columns must be in character form, showing only field digitsand 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 dayof the month, hh the hour, mi the minute, ss the second, and fff the fractional partof a second.

Specifying a dbload Command FileBefore you can use dbload, you must first create an ASCII command file thatmaps fields from one or more input files into columns of one or more tableswithin your database. This command file must specify two kinds ofinformation:

• One or more FILE statements, to define data fields within the records ofthe input file(s)

• One or more INSERT statements, to indicate how to place the new datainto the columns of the database table(s)

INSERT statements in dbload command files resemble INSERT statements inSQL, except that they cannot incorporate SELECT statements (since the dataare not yet in any table). In effect, the most recent FILE statement replacesSELECT in defining the list of data values for a dbload INSERT statement toenter as new rows.

E-12 INFORMIX-4GL Utility Programs

Page 707: Manual Informix

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. Anexplanation of these terms, notes, and an example follow.

ExplanationFILE is a required keyword.

filename is the pathname of an input file, enclosed between a pair ofquotation ( " ) marks.

DELIMITER is a keyword that is required if filename has variable-lengthdata records.

c is the field delimiter (enclosed in quotes) between fields of avariable-length data record, and before the NEWLINE char-acter that terminates each record.

nfields is an integer, specifying the number of fields in each vari-able-length data record.

fieldn is a name that you assign to a data field within a fixed-lengthrecord of filename.

start is an integer, indicating a character position within a fixed-length record.

-end is a hyphen ( - ) and an integer, indicating (with start) a rangeof character positions.

NULL is a keyword to specify a NULL symbol.

null-str is a quoted string, specifying a data value for which dbloadshould substitute a NULL.

INSERT INTO are required keywords.

tablename identifies a table in which to store the data.

INFORMIX-4GL Utility Programs E-13

Page 708: Manual Informix

The dbload Utility

column-list is a list of column names within tablename, separated bycommas.

VALUES is an optional keyword to specify a list that can include con-stants and data field names.

value-list is a comma-separated list of constants and/or data fieldnames from filename.

Notes1. The dbload utility recognizes valid owner.table references.

2. You need UNIX read permission for filename, and you must also be grantedthe 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 recorddefined with the DELIMITER option.

5. Use a colon ( : ) to separate character position or range values in each datafield definition. The list of field definitions must be enclosed in parenthe-ses and separated by commas.

6. The same character position can be repeated in the FILE specification of afield, or in different fields. (See the command file example that followsthese notes.)

7. The scope of reference of a null-str is the field for which you define it, butyou 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 INSERTstatement can reference field names assigned by the user or by dbload inthe previous FILE statement.

9. If your INSERT statement omits the column-list, then the default columnsare every column in tablename. If you do not specify a value-list, then thedefault 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 numbersof elements.

11. If the column-list includes fewer columns than tablename, dbload attemptsto insert NULL values in the remaining columns. If a NOT NULL restric-tion or UNIQUE CONSTRAINT would be violated, the insertion fails, andan error message appears.

12. Inserted data types correspond to the explicit or default column-list. If thedata field width is different from its corresponding character column,

E-14 INFORMIX-4GL Utility Programs

Page 709: Manual Informix

The dbload Utility

inserted values are padded with blanks if the column is wider, or are trun-cated 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. Ifthe delimiter c (or a backslash) appears as a literal character, you mustprefix it with a backslash ( \ ) in the input file.

15. If you specify DELIMITER, the same delimiter must be used throughoutthe input file and must appear in quotes in the FILE statement. You mustremember to place the delimiter immediately before the NEWLINE char-acter that marks the end of each record. (If you omit this delimiter, anerror results whenever the last field of a record is empty.)

ExamplesFILE "datafile1" (fld 1 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 tab2VALUES (fld1, fld3, "kevin" , . . . , fldN) ;

INSERT INTO tab3 ; {no column or values list provided}

FILE "datafile.2" DELIMITER "|" 8 ; {variable-length fields}

INSERT INTO tab1VALUES (f01, f02, "kevin", "234" , . . . , f08) ;

INSERT INTO tab4 ;

Note: The ellipses (. . .) in this example are typographic conventions that cannotappear in command files. Unless you use the DELIMITER option, for example, youmust explicitly list every field that a FILE statement defines. Each statement in thisexample is described in the pages that follow.

FILE "datafile1" (fld 1 1 - 10 : 13 : 5 - 22 NULL = "str1" ,

Here datafile1 is the input file, and fld1, fld2, fld3, through fldN are user-assigned field names in its fixed-length data records. In this example, fld1consists of the characters in positions 1 through 10, 13, and 5 through 22 ofevery datafile1 record. (Each record ends with a NEWLINE character.) Noticethat the characters 5 through 10 and 13 appear twice in fld1, and characters10, 13, and 21 appear in fld1 and fld2.

In field fld1, the NULL symbol is defined as ‘‘str1 .’’ A NULL value is enteredwhenever ‘‘str1 ’’ is read in fld1.

INFORMIX-4GL Utility Programs E-15

Page 710: Manual Informix

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 through50, 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 fldNcontains characters in positions 9, and 16 through 19. The NULL value isdefined as ‘‘string .’’

INSERT INTO tab1 (col1, col2, col9 , . . . , colN) ;

An INSERT statement follows. Here col1, col2, col9, and so on are the actualdatabase column names in table tab1. Since no value list is provided, dbloadtakes the values in the fields defined in the preceding FILE statement. Itinserts the data from fld1 into col1, from fld2 into col2, from fld3 into col9, andso forth, until the value from fldN is inserted into colN. (Columns 4 through8 are skipped, so the new rows will have NULL values there, if the columnspermit NULLs.)

INSERT INTO tab2VALUES (fld1, fld3, "kevin" , . . . , fldN) ;

Since no column list is provided, dbload reads the names of all the columnsin tab2 from the system catalogs. Values to load into each column are speci-fied by field names from the previous FILE statement or as constants. Data infld1 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 isinserted 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 datavalues. To create a default column-list, dbload checks the system catalogs forthe names of all the columns in table tab3.

The default value-list comes from the most recent FILE statement, in this casethe first statement in the command file. Data from fld1 go into the first col-umn, data from fld2 into the second, and so forth, with data from field fldNgoing into the Nth column.

Note: This statement requires that the field list in the FILE statement have a one-to-one 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 willreceive an error message on each record.

The loading process terminates when the total number of records that cannotbe inserted as new rows exceeds a limit that you can specify at the dbloadcommand line (by using the -c option).

FILE "datafile.2" DELIMITER "| " 8 ; {variable-length fields}

E-16 INFORMIX-4GL Utility Programs

Page 711: Manual Informix

The dbload Utility

The DELIMITER clause tells dbload that file datafile.2 has variable-lengthfields, and that the vertical-bar character ( | = ASCII 124) separates each field.

Here 8 is the number of fields in each input record. Fields are automaticallyassigned the names f01, f02, f03, and so on.

INSERT INTO tab1VALUES (f01, f02, "kevin", "234" , . . . , f08) ;

A value-list but no column-list is specified, so dbload reads all the columnnames of tab1 from the system catalogs. Here the value in field f01 goes intothe first column, the f02 value into the second, the constant ‘‘kevin ’’ into thethird, the constant ‘‘234 ’’ into the fourth, and so forth, until the value in fieldf08 is inserted into the last column.

You must reference fields in a variable-length data file with the letter f fol-lowed by a two-digit number: f01 , f02 , f10 , and so on. Other formats likefld01 or f3 are incorrect.

INSERT INTO tab4 ;

Since no column-list or value-list is provided, dbload finds all the names of col-umns in table tab4 in the system catalogs. The value-list is all the fieldsdefined in the previous FILE statement. (Notice that this is not the same FILEstatement that was used with table tab3.)

If these values have a one-to-one correspondence with the columns, the valuefrom field f01 goes into the first column, the value from f02 into the secondcolumn, and so on, until the value in f08 is placed in the last column. An errorresults if 8 is not the number of columns in table tab4.

Specifying a dbload Command LineAfter you have created a valid command file, you invoke dbload at the oper-ating system prompt. The argument list that you include in your commandline determines whether the program operates in command mode or interactivemode.

If you enter the keyword dbload without any arguments, the screen dis-plays a syntax summary for dbload usage, and control returns to the operat-ing system.

INFORMIX-4GL Utility Programs E-17

Page 712: Manual Informix

The dbload Utility

To use dbload to read and execute a command file, you must enter a com-mand line that includes at least one of its required specifications. The follow-ing elements are required in a dbload command line:

dbload { -d database | -c comfile | -l logfile } . . .

dbload invokes the dbload utility.

-d database identifies a database to receive the new data.

-c comfile identifies a dbload command file.

-l logfile identifies a file to log any error messages.

The following sections describe both the interactive and command modes ofdbload.

Running dbload InteractivelyIf you specify part (but not all) of the required information after the dbloadkeyword, the program automatically enters interactive mode and promptsyou for additional specifications. Depending on what you entered at the com-mand 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 thatdbload cannot insert into the database, as well as diagnostic information.

• Whether you only want dbload to check the syntax of the FILE andINSERT statements in your command file, without changing the database.

• How many bad input records can be encountered before dbload stopsinserting new rows.

• How many input file records to read before committing new rows to thedatabase, if your database supports transactions.

• Whether to discard or to commit to the database any rows that were suc-cessfully read between the last COMMIT and the first bad record thatexceeds 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 processingbegins.)

After you enter these specifications or press RETURN to accept the defaultvalues that appear in the prompts, the screen is cleared, and the dbload util-ity begins execution.

E-18 INFORMIX-4GL Utility Programs

Page 713: Manual Informix

The dbload Utility

Running dbload in Command ModeIf a valid dbload command line includes the required database, command file,and error log specifications, with or without any additional options, programexecution begins. The complete syntax of dbload is indicated here:

Syntaxdbload -d database -c comfile -l logfile

[ -e num1 ] [ -n num2 ] [ -i num3 ] [ -p ] [ -r ] [ -s [ > outfile ] ]

Explanationdbload is a required keyword.

-d database is the name of a database to receive the data.

-c comfile is the pathname of a dbload command file.

-l logfile is the pathname of an error logging file.

-e num1 is the number of bad records that dbload will read before itterminates (where num1 is an integer).

-n num2 displays a message after each batch of num2 new rows areinserted (where num2 is an integer).

-i num3 ignores the first num3 input records (where num3 is aninteger).

-p prompts for instructions if the number of bad recordsexceeds num1.

-r instructs dbload not to lock the table(s). (Otherwise, table-level locking occurs during loading.)

-s instructs dbload only to check the syntax of the statementsin comfile, without inserting any data.

> outfile is an optional > symbol and the name of a file in which tosave output from the syntax check.

Notes1. 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 threerequired options, dbload prompts you for additional specifications.

2. You can prefix comfile, logfile, or outfile with a pathname.

INFORMIX-4GL Utility Programs E-19

Page 714: Manual Informix

The dbload Utility

3. You should run dbload with the -s or -s > outfile options before you beginloading data. These options perform a syntax check on the FILE andINSERT statements in comfile and ignore any other options except -d data-base and -c comfile. The screen displays comfile with any errors markedwhere they are found.

4. If you do not specify a value for num1, the default is 10 bad records, so theprogram stops loading when it reads the 11th bad record. If you set num1at zero, dbload terminates when it reads the first bad record.

5. If your database supports transactions, dbload reads and inserts a batchof num2 records between each COMMIT. If you do not specify a value fornum2, the default is 100 records.

6. The -i option instructs dbload to ignore the first num3 lines in the inputfile, so processing does not begin until dbload has read num3 NEWLINEcharacters. This option is useful, for example, if your most recent dbloadsession with the same command file ended after 240 lines of input. Youcan resume loading at line 241 by setting num3 equal to 240. It is also use-ful if header information in the input file precedes the data records.

7. After (num1 + 1) bad records in a database with transactions, the -poption prompts you to roll back or to commit any rows inserted since thelast transaction. The default is to commit.

8. If you press the Interrupt key, dbload terminates and discards any newrows that have been inserted but not yet committed to the database (if thedatabase has transactions).

9. The presence of indexes greatly affects the speed with which the dbloadutility loads data. For best performance, drop any indexes on the tablesreceiving the data before you run dbload. You can create new indexesafter dbload has finished.

ExamplesThe following example shows a dbload command line at the system promptthat 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 is the name of the database to receive the data.

-c cfyl is the name of the dbload command file.

-l lfyl is the name of the error-log file.

E-20 INFORMIX-4GL Utility Programs

Page 715: Manual Informix

The dbload Utility

-e 5 specifies that dbload will log up to five bad records. The pro-gram terminates if a 6th bad record is encountered.

-n 75 specifies that screen messages will indicate when successivebatches of 75 rows have been inserted (or committed, in adatabase with transactions).

-i 20 tells dbload to ignore the first 20 lines of the data file. Pro-cessing begins at the 21st line.

-p prompts you to commit or discard any uncommitted rowsafter six bad records.

-r tells dbload not to lock the table(s) of the stores databasethat are being accessed by dbload while the new rows arebeing inserted. This allows other users to access the sametable(s) during the dbload operation. Unless you specify the-r option, table-level locking occurs.

Notice that the names of the input file and the table(s) to receive the data donot appear explicitly in the command line. These names must be specifiedwithin the dbload command file, which is called cfyl in this example.

INFORMIX-4GL Utility Programs E-21

Page 716: Manual Informix

The dbschema Utility

The dbschema UtilityYou can use the dbschema utility to produce quickly an SQL command filecontaining the CREATE TABLE, CREATE INDEX, and CREATE VIEW state-ments required to replicate an entire database or a selected table. In addition,dbschema can produce all CREATE SYNONYM and GRANT statements ineffect for the database or a selected table or view. You must be the DBA orhave CONNECT or RESOURCE permission to the database before you can rundbschema.

By default, dbschema produces all CREATE TABLE, CREATE VIEW, CREATEINDEX, CREATE SYNONYM, and GRANT statements in effect for the entiredatabase. By including the appropriate command-line option, you can limitthe output to a selected table or view, or produce synonyms and permissionsfor a particular user.

dbschema uses the owner.object convention when it generates any CREATETABLE, CREATE INDEX, CREATE SYNONYM, CREATE VIEW, or GRANT state-ments, and when it reproduces any UNIQUE CONSTRAINTs. As a result, ifyou use the dbschema output to create a new object (table, index, view, orsynonym), the new object is owned by the owner of the original object. If youwant to change the owner of the new object, you must edit the dbschema out-put 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 tooutput CREATE TABLE and CREATE INDEX statements or theCREATE VIEW statement. If you specify all for tabname,dbschema outputs the SQL statements for all database tablesand views.

-s sname specifies the user for whom you want dbschema to output theCREATE SYNONYM statements. If you specify all for sname,dbschema outputs all CREATE SYNONYM statements. If youinclude the -t option, dbschema produces the CREATESYNONYM statements only for the indicated tabname.

-p pname specifies the user for whom you want dbschema to output per-mission statements. If you specify all for pname, dbschemaoutputs the GRANT statements for all users. If you include the-t option, dbschema produces the GRANT statements only forthe indicated tabname.

-d database specifies the name of the database.

E-22 INFORMIX-4GL Utility Programs

Page 717: Manual Informix

The dbschema Utility

filename specifies the name of the file in which to save the dbschemaoutput. If filename is not provided, dbschema outputs to thescreen.

Notes1. 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 thedatabase before you can run dbschema on it.

3. When you include the -t option, dbschema produces SQL statements onlyfor the indicated tabname. The dbschema utility uses the tabname to filterthe output. If you use the -t option with the -p and -s options, only theCREATE 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 differentowners, you must first change the owner names in the output file.

5. All SERIAL fields included in CREATE TABLE statements output bydbschema have a starting value of one, regardless of their original start-ing value.

6. In the dbschema output, the AS keyword is used to indicate the grantorof 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, youmay need to grant certain permissions before running the output as anSQL script. Consider the following GRANT statement:

GRANTtab-privilege ON user1.tablename TO "user2 " AS " user3 "

Before this statement can be run to create another schema, the followingmust 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 inyour DBPATH environment variable.

INFORMIX-4GL Utility Programs E-23

Page 718: Manual Informix

The dbschema Utility

ExamplesThe following statement outputs the SQL statements relating to the customertable 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 thecustomer 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 siz e = 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 thestores 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 thatreplicate 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

Page 719: Manual Informix

The dbupdate Utility

The dbupdate UtilityDatabases created through Informix products that used an early implemen-tation of SQL (Version 1.1 or earlier) have a different structure than databasescreated through products using the current implementation. The currentstructure includes additional system catalogs, content changes to some exist-ing system catalogs (see Appendix B), and the introduction of NULL values.

A database will have the old structure if it was created by an applicationusing Version 2.0 (or earlier) of INFORMIX-ESQL/C, INFORMIX-ESQL/COBOL, or INFORMIX-SQL or Version 1.0 of INFORMIX-4GL. Such a databasecannot be used with current application development tools or databaseengines until the database is converted to the current structure. You can con-vert old databases to the current structure through the dbupdate utility.

Using dbupdateTo convert an old database to the new structure, execute the followingcommand:

dbupdate [ -b | -n ] old-database-name new-database-name

The dbupdate utility creates a new database in the current directory with thename new-database-name, and copies the data from the old system catalogs tothe new system catalogs, making the appropriate changes.

If you do not use the -b or -n option, dbupdate converts the value of all CHARtype columns with blank data to NULL and, for each number column, asksyou whether it should convert zero values to NULL values.

The -b option causes dbupdate to leave blank data in CHAR columns asblanks. The -n option alters the system catalogs to define all columns as NOTNULL, 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 representationof negative DECIMAL values.

When dbupdate finishes, you have two database directories (the new and theold) with two separate system catalogs, but the data and index files areshared (linked). To complete the update, you should remove the old databasedirectory.

INFORMIX-4GL Utility Programs E-25

Page 720: Manual Informix

The dbupdate Utility

No NULL DatabasesYou may want to avoid dealing with NULL values and their three-valuedlogic. 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 theDATABASE 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 specifica-tion files.

E-26 INFORMIX-4GL Utility Programs

Page 721: Manual Informix

The mkmessage Utility

The mkmessage UtilityThe mkmessage utility converts ASCII source files that contain user messagesinto a format that 4GL programs can use in on-line displays. This sectiondescribes how to use mkmessage with help files and with customized run-time error messages.

Programmer-Defined Help MessagesWhen executing an INFORMIX-4GL program, the user can request helpwhenever the program is waiting for user input. This can occur while makinga menu selection, while inputting data to a form, or while responding to aprompt. You can supply help messages that are displayed whenever the userpresses the Help key (specified in the OPTIONS statement). These messagescan be specific to the menu option currently highlighted, or to the INPUT,INPUT ARRAY, or PROMPT statement.

Message Source FilesINFORMIX-4GL looks for the appropriate help message in the help file thatyou specify in an OPTIONS statement, using the HELP FILE option. You canhave several help files, but only one can be in effect at a time. The structureof the message source file is very simple:

Syntax.nummessage-text

. . .[ . . . ]

Explanation.num is a period, followed by an integer.

message-text is a line of characters and/or blanks.

Notes1. Each line must end in a RETURN.

2. Each help message should be preceded by a line with nothing on it but aperiod (in the first column) and a unique integer num.

INFORMIX-4GL Utility Programs E-27

Page 722: Manual Informix

The mkmessage Utility

3. The message-text starts on the next line, and continues until the next num-bered line.

4. You can use the integer num to identify the help message in your INFOR-MIX-4GL programs. (See the INPUT, INPUT ARRAY, MENU, andPROMPT statement descriptions in Chapter 7.)

5. All blank lines between two numbered lines are considered part of themessage that belongs to the first of the two numbers.

6. Lines beginning with # are considered comment lines, and are ignored bymkmessage.

7. If the text of a message occupies more than 20 lines, INFORMIX-4GL auto-matically breaks the message into ‘‘pages’’ of 20 lines. You can changethese default page breaks by entering CTRL-L in the first column of a linein your message file to start a new page.

8. INFORMIX-4GL handles clearing and redisplaying the screen.

ExamplesFor an example, see the helpdemo.src file from the demonstration applica-tion in Appendix A. (See also the section ‘‘Creating a Help File’’ in Chapter 8of the INFORMIX-4GL User Guide.)

Creating Executable Message FilesOnce you have created your message source file, you can process it for use byINFORMIX-4GL with this syntax:

Syntaxmkmessage helpfile.src helpfile.out

Explanationhelpfile.src is an ASCII source file of help messages.

helpfile.out is the pathname of the executable output file.

E-28 INFORMIX-4GL Utility Programs

Page 723: Manual Informix

The mkmessage Utility

Notes1. You can give the input and output help files any valid names and exten-

sions in place of those shown above.

2. You can specify the output help file name in the OPTIONS statement toidentify it as the current help file.

3. If you want to use help messages from the help file on a field-by-fieldbasis in an INPUT or INPUT ARRAY statement, you must use the infield()and showhelp( ) library functions that are supplied with INFORMIX-4GL.

ExamplesThe example that follows illustrates the use of these functions:

OPTIONSHELP FILE "stores.hlp",HELP KEY F1

...INPUT pr_fname, pr_lname, pr_phone

FROM fname, lname, phone HELP 101ON KEY (F1)

CASEWHEN INFIELD(lname)

CALL showhelp(111)WHEN INFIELD(fname)

CALL showhelp(112)WHEN INFIELD(phone)

CALL showhelp(113)OTHERWISE

CALL showhelp(101)END CASE

END INPUT

Customized Error MessagesYou can also use the mkmessage utility to customize run-time error mes-sages. INFORMIX-4GL is distributed with a file called 4glusr.msg. This ASCIIfile contains some common error messages (as listed later in this volume),including the messages for run-time errors that cannot be trapped by theWHENEVER ERROR statement, and messages that support the 4GL Helpmenu. The 4glusr.iem file contains the executable version of this file.

You can edit the messages in 4glusr.msg with a text editor (for example, tomake them specific to a 4GL application, or to translate them into another lan-guage). Be sure to preserve the required numeric codes, prefixed by a period( . ) to identify each message.

INFORMIX-4GL Utility Programs E-29

Page 724: Manual Informix

The mkmessage Utility

If you choose to modify the contents of the 4glusr.msg message file, you mustspecify 4glusr.iem in your mkmessage command line as the object file name:

mkmessage source-file-name 4glusr.iem

The executable file 4glusr.iem is initially installed in the directory $INFOR-MIX/msg. INFORMIX-4GL looks for message files in one of two directories,namely /$INFORMIXDIR/$DBLANG or else/$INFORMIXDIR/msg. If $DBLANG is defined, 4GL looks only in/$INFORMIXDIR/$DBLANG. If this is not defined, 4GL looks only in/$INFORMIXDIR/msg. You must place the newly modified file 4glusr.iemin the appropriate /$INFORMIXDIR/msg or /$INFORMIXDIR/$DBLANGdirectory.

E-30 INFORMIX-4GL Utility Programs

Page 725: Manual Informix

The sqlconv Utility

The sqlconv UtilityThe sqlconv utility is provided for the Database Administrator who wants touse INFORMIX-SQL, INFORMIX-ESQL/C, or INFORMIX-4GL with a databasethat was created with the non-SQL product INFORMIX (Version 3.2 or 3.3).From the INFORMIX database, sqlconv aids a user in creating a new SQL-compatible database. It leaves the old database intact.

This appendix discusses the steps necessary to convert an INFORMIX data-base to an SQL-compatible database. The new database can be used withINFORMIX-SQL, INFORMIX-ESQL/C, or INFORMIX-4GL.

If you have purchased INFORMIX-SQL or INFORMIX-ESQL/C in addition toINFORMIX-4GL, and you have already run the sqlconv utility provided withthe other product, you do not need to run sqlconv again.

This appendix describes two methods you can use to accomplish a databaseconversion. The method you should use depends on the disk space con-straints of your system.

Caution: sqlconv will not convert INFORMIX database permissions. You mustgrant new permissions on tables and fields after your new 4GL database has been cre-ated and loaded.

INFORMIX-4GL reserved words are not the same as INFORMIX reserved words. Ifyou receive a syntax error while running your new 4GL programs, make sure thatyour table and field names are not among the new reserved words. For a list ofreserved words, see Appendix D in this manual.

Make sure all INFORMIX composite fields are indexed. Indexed composite fields willhave composite indexes created for them.

If you have used the LOCATION option to spread an INFORMIX database across anumber of directories, converting the database using sqlconv places all of these filesin the new .dbs directory.

You cannot specify a new starting number for a SERIAL column.

INFORMIX-4GL Utility Programs E-31

Page 726: Manual Informix

The sqlconv Utility

Conversion Procedures

If There Is No Shortage of Disk Space

You can convert an entire INFORMIX database to an SQL compatible databasefor use with INFORMIX-4GL at one time if there is no shortage of disk space.

To convert an entire database at once, you must have available on the disk atleast three times the amount of space required by all the tables in the databaseplus additional space for the 4GL system files. The following steps outline theprocess of converting an entire database at once:

1. Make certain that INFORMIX and INFORMIX-4GL are included in yoursearch path.

2. Set the INFORMIXDIR environment variable to point to the INFOR-MIX-4GL directory.

3. Change your current directory to the directory that contains your INFOR-MIX database.

4. Create a backup copy of the INFORMIX database.

5. Enter

sqlconv -e databasename

where databasename is the name of the INFORMIX database that you wantto convert. Do not include a filename extension. This command generatesan INFORMER script file (indicated by a .uld extension), an INFOR-MIX-4GL program (indicated by a .4gl extension), and a dbload com-mand file (indicated by a .cmd extension).

6. Enter

informer databasename databasename . uld

This command unloads the database files (in ASCII format) to unload files(indicated by a .unl extension) for each table in the database.

E-32 INFORMIX-4GL Utility Programs

Page 727: Manual Informix

The sqlconv Utility

7. If you have the C Compiler Version of INFORMIX-4GL, enter

c4gl databasename . 4gl -o databasename . out

This command compiles the 4GL program created in Step 5, and createsan executable file with extension .out.

If you have the RDS version of INFORMIX-4GL, enter

fglpc databasename .4gl

This creates a p-code file databasename.4go from the 4GL program thatyou created in Step 5.

8. If you have the C Compiler Version of INFORMIX-4GL, enter

databasename . out

This command runs the INFORMIX-4GL program that you compiled inStep 7 and re-creates the database, tables, and indexes in SQL format.

If you have the RDS version of INFORMIX-4GL, enter

fglgo databasename .4go

This executes the p-code file that you created in Step 6, and re-creates thedatabase, tables, and indexes in SQL format, but it does not load the data.

9. Enter

dbload -d databasename -c databasename . cmd -l errlog

This command loads the data from the .unl files (generated by informer)into the appropriate tables, and creates an errlog file, which contains diag-nostic information about any rows that were not successfully loaded. Formore information on dbload, see “The dbload Utility” in this appendix.

10. The final step in the conversion procedure is to remove all the old data-base files, and the .uld, .4gl, .cmd, .unl, .out or .4go files from yourdirectory, and any .ec or .c files that may have been created if you have theC Compiler Version of INFORMIX-4GL. Do not remove your forms andreports. You can update these later.

If There Is a Shortage of Disk Space

The following method is more economical in terms of disk space, but it is amore involved and time-consuming process than the method discussed inthe previous section. Use this method if you do not have at least three timesthe amount of space required by the database.

INFORMIX-4GL Utility Programs E-33

Page 728: Manual Informix

The sqlconv Utility

The following steps outline the conversion of the example INFORMIX data-base, payroll, to an SQL-compatible database for use with 4GL:

1. Make certain that INFORMIX and INFORMIX-4GL are included in yoursearch path.

2. Set the INFORMIXDIR environment variable to point to the INFOR-MIX-4GL directory.

3. Change your current directory to the directory that contains your INFOR-MIX database.

4. Create a backup copy of the INFORMIX database.

5. Enter

sqlconv -e payroll

Do not include a filename extension. This command generates anINFORMER script file (indicated by a .uld extension), an 4GL program(indicated by a .4gl extension), and a dbload command file (indicated bya .cmd extension).

6. If you have the C Compiler Version of INFORMIX-4GL, enter

c4gl payroll.4gl -o payroll.out

This command compiles the 4GL program that you created in Step 5, andcreates an .out executable file.

If you have the RDS version of INFORMIX-4GL, enter

fglpc payroll.4gl

This creates a p-code file payroll.4go from the 4GL program that you cre-ated in Step 5.

7. If you have the C Compiler Version of INFORMIX-4GL, enter

payroll.out

This command runs the INFORMIX-4GL program you compiled in Step 6,and re-creates the database, tables, and indexes in SQL format, but it doesnot load the data.

If you have the RDS version of INFORMIX-4GL, enter

fglgo payroll.4go

This executes the p-code file that you created in Step 6, and re-creates thedatabase, tables, and indexes in SQL format, but it does not load the data.

E-34 INFORMIX-4GL Utility Programs

Page 729: Manual Informix

The sqlconv Utility

8. Enter

cat payroll.uld

The statements in the payroll.uld file outline the first steps of the conver-sion operation. You must execute each of these statements separately. Youmay find it helpful to print a copy of the payroll.uld file for easy refer-ence.

9. Enter

informer payroll

At the INFORMER prompt, enter the first line of the payroll.uld fileexactly as it appears. This creates the unload file for the first table. Exitfrom INFORMER.

10. The .cmd file describes the form of the data and contains the INSERT INTOstatements indicating how this data is to be placed in the database files.The INSERT INTO statements are necessary to load the data into the newlycreated database. You must execute each of the statements separately. Todo this, create a copy of the payroll.cmd file for each INSERT INTO state-ment and make sure you include the .cmd extension to the filename ofeach new file. In this instance, we have named the files one.cmd andtwo.cmd.

11. Edit the one.cmd file using your system editor, and remove all but thefirst INSERT INTO statement from the file. Exit from the file.

12. Execute the first INSERT INTO statement in the one.cmd file by entering

dbload -d payroll -c one.cmd -l errlog

This command loads the data from the .unl file into the appropriate tableand creates an errlog file, which contains diagnostic information aboutany rows that were not successfully loaded. A statement appears on thescreen indicating how many rows were loaded into the file. For moreinformation on dbload, see “The dbload Utility” in this manual.

13. Before you can perform the same operations on any other database tables,you must free additional disk space by erasing the INFORMIX versions ofthe recently created INFORMIX-4GL files. To erase these files, enter

dbstatus payroll

14. At the dbstatus prompt, enter

erase file filename

where filename is the name of the file referred to in the .cmd file created inStep 11. Exit from dbstatus.

INFORMIX-4GL Utility Programs E-35

Page 730: Manual Informix

The sqlconv Utility

15. Erase the unload file for this same file by entering from the command line

rm filename .unl

16. Continue to unload each table, one at a time, from the INFORMIX data-base and then load it into the INFORMIX-4GL database. Do this byrepeating Steps 9 through 15. Remember to make a copy of the .cmd filefor each INSERT INTO statement it contains. Each copy must have aunique name and must end in the .cmd extension. The correct filenamemust be included on the command line each time you run the dbloadcommand.

Repeat these steps until all load statements in the payroll.cmd file havebeen executed. This operation loads the actual data into the newly createddatabase.

17. Check the contents of the data files in the newly created database to makesure you have successfully converted your INFORMIX database.

18. When all tables in the database have been converted, erase the .uld, .4gl,.cmd, .out, or .4go files from your directory (and any .ce or .c files thatmay have been created if you have the C Compiler Version of INFOR-MIX-4GL) and drop the INFORMIX database.

Caution: You cannot rerun sqlconv after you have erased a table. The newscripts generated by the command do not contain the information necessary to con-vert the table.

E-36 INFORMIX-4GL Utility Programs

Page 731: Manual Informix

The upscol Utility

The upscol UtilityThe upscol utility program allows you to create and modify the syscolvaland syscolatt tables, which contain default information for fields in screenforms that correspond to database columns. Chapter 4 describes these tablesand their use by INFORMIX-4GL.

You invoke the upscol utility by entering the command upscol in responseto the system prompt. After you select a database (db-name) at the CHOOSEDATABASE screen, the following menu appears:

UPDATE SYSCOL: Validate Attributes ExitUpdate information in the data validation table.

-------------------- db-name ------------------- Press CTRL-W for Help --------

The options in the UPDATE SYSCOL Menu are

Validate Update the information in syscolval.

Attributes Update the information in syscolatt.

Exit Return to the operating system.

If you select either Validate or Attributes, upscol checks whether the corre-sponding table exists and, if not, asks whether you want to create it. In thetext that follows, the corresponding table is called syscol. If you choose not tocreate it, enter n, and you will return to the UPDATE SYSCOL Menu.

If the data validation table already exists, or if you enter y to create it, upscoldisplays the CHOOSE TABLE screen, and prompts you for the name of a table(tab-name) in db-name. After you select a table, the CHOOSE COLUMN screenprompts you to select the name of a column (col-name) whose default valuesyou want to modify in syscol.

INFORMIX-4GL Utility Programs E-37

Page 732: Manual Informix

The upscol Utility

The selected table and column names appear, along with the database name,on the dividing line beneath the next menu, which is called the ACTIONMenu:

ACTION: Add Update Remove Next Query Table Column ExitAdd an entry to the data validation [or screen display attribute] table.

--------- db-name:tab-name:col-name ------------ Press CTRL-W for Help --------

Now upscol displays the first row of syscol that relates to tab-name andcol-name in the work area beneath this menu. If no such entries exist, a mes-sage stating this appears on the Error line.

The options in the ACTION Menu are

Add Add new rows to the syscol table.

Update Update the currently displayed row.

Remove Remove the currently displayed row (after a prompt forverification).

Next Display the next row of syscol.

Query Restart the display at the first row of syscol for tab-name andcol-name.

Table Select a new database table and column.

Column Select a new column within tab-name.

Exit Return to the UPDATE SYSCOL Menu.

E-38 INFORMIX-4GL Utility Programs

Page 733: Manual Informix

The upscol Utility

Adding or Updating Under the Validate OptionWhen you select Add in the ACTION Menu after choosing the Validateoption in the UPDATE SYSCOL Menu, the VALIDATE Menu appears:

VALIDATE: Autonext Comment Default Include Picture Shift Verify ExitAutomatically proceed to next field when at end of current field.

--------- db-name:tab-name:col-name ------------ Press CTRL-W for Help --------

The options are attribute names and their selection has the following effects:

Autonext Produces a menu with three options, Yes, No, and Exit. Exitreturns you to the VALIDATE Menu. The default is No.

Comment Produces a prompt to enter a Comment line message. Noquotation marks are required around the comment, but itmust fit on a single screen line.

Default Produces a prompt to enter the DEFAULT attribute, format-ted as described in Chapter 4. Quotation marks are requiredwhere necessary to avoid ambiguity.

Include Produces a prompt to enter the INCLUDE attribute, format-ted as described in Chapter 4. Quotation marks are requiredwhere necessary to avoid ambiguity.

Picture Produces a prompt to enter the PICTURE attribute, formattedas described in Chapter 4. No quotation marks are required.

Shift Produces a menu with four options, Up, Down, None, andExit. Up corresponds to the UPSHIFT attribute and Down tothe DOWNSHIFT attribute. Exit returns you to the VALIDATEMenu. The default is None.

Verify Produces a menu with three options, Yes, No, and Exit. Exitreturns you to the VALIDATE Menu. The default is No.

Exit Returns you to the ACTION Menu.

The upscol utility adds or modifies a row of syscolval after you completeeach of these options except Exit.

INFORMIX-4GL Utility Programs E-39

Page 734: Manual Informix

The upscol Utility

The Update option on the ACTION Menu takes you immediately to theATTRIBUTE Menu or prompt corresponding to the current attribute for thecurrent column. You can look at another attribute for the current column byusing the Next option, start through the list again by using the Query option,remove the current attribute with the Remove option, and select a new col-umn or table with the Column or Table options.

Adding or Updating Under the Attribute OptionWhen you select Add or Update in the ACTION Menu after choosing theAttribute option in the UPDATE SYSCOL Menu, the ATTRIBUTE Menuappears:

ATTRIBUTE: Blink Color Fmt Left Rev Under Where Discrd_Exit Exit_SetSet Field blinking attribute

--------- db-name:tab-name:col-name ------------ Press CTRL-W for Help --------

If you are adding a new row to syscolatt, a default row is displayed in thework area below the menu. If you are updating an existing row of syscolatt,the current row appears. Since no entry is made in syscolatt until you selectExit_Set, you can alter all the attributes before deciding to modify syscolatt(Exit_Set) or to abort the changes (Discrd_Exit).

The options of the ATTRIBUTE Menu are screen attribute names, and theirselection has the following effects:

Blink Produces a menu with three options, Yes, No, and Exit. Thedefault is No.

Color Produces a menu with the available colors (color terminals)or intensities (monochrome terminals) for display of tab-name.col-name. The colors displayed are those in the localcolornames file, whose format is described in Appendix I. Ifno such file exists locally, upscol looks in $INFORMIXDIR/incl. If the file does not exist there, upscol uses the defaultcolor list (see Chapter 4). You can toggle back and forthamong the colors or intensities using CTRL-N.

E-40 INFORMIX-4GL Utility Programs

Page 735: Manual Informix

The upscol Utility

Fmt Prompts you for the format string to be used when tab-name.col-name is displayed.

Left Produces a menu with three options, Yes, No, and Exit. Yescauses numeric data to be left justified within the screenfield. The default is No.

Rev Produces a menu with three options, Yes, No, and Exit. Yescauses the field to be displayed in reverse video. The defaultis No.

Under Produces a menu with three options, Yes, No, and Exit. Yescauses the field to be displayed with underlining. Thedefault is No.

Where Prompts for the values and value ranges under which theseattributes will apply. See Chapter 4 for allowable syntax.

Discrd_Exit Discards the indicated changes and returns to the ACTIONMenu.

Exit_Set Enters the indicated changes into the syscolatt table andreturns to the ACTION Menu.

After you complete each of these options except Discrd_Exit, upscol adds ormodifies a row of syscolatt.

Note: Whoever runs the upscol utility produces a pair of tables, syscolval andsyscolatt, that provide default values for all the users of a database that is not MODEANSI.

If the current database is MODE ANSI, however, the user who runs upscol becomesthe owner of the syscolatt and syscolval tables specified at the upscol menus, butother users can produce their own user. syscolval and user.syscolatt tables. Thedefault specifications in an upscol table are applied by INFORMIX-4GL only to col-umns of database tables that have the same owner as the upscol table. (For details,see the section “The upscol Tables in a MODE ANSI Database” in Chapter 4, andthe notes on the INITIALIZE and VALIDATE statements in Chapter 7.)

INFORMIX-4GL Utility Programs E-41

Page 736: Manual Informix

The upscol Utility

E-42 INFORMIX-4GL Utility Programs

Page 737: Manual Informix

Appendix

F

DECIMALFunctions for CThe data type DECIMAL is a machine-independent methodfor the representation of numbers of up to thirty-two signif-icant digits, with or without a decimal point, and exponentsin the range -128 to +126. INFORMIX-4GL provides routinesthat facilitate the conversion of DECIMAL-type numbers toand from every data type allowed in the C language.

DECIMAL-type numbers consist of an exponent and a man-tissa (or fractional part) in base 100. In normalized form, thefirst digit of the mantissa must be greater than zero.

When used within a C program, DECIMAL-type numbersare stored in a C structure of the type shown below.

#define DECSIZE 16

struct decimal{short dec_exp;short dec_pos;short dec_ndgts;char dec_dgts[DECSIZE];};

typedef struct decimal dec_t;

The decimal structure and the typedef dec_t shown abovecan be found in the header file decimal.h. Include this filein all C source files that use any of the decimal routines:

#include <decimal.h>

Page 738: Manual Informix

DECIMAL-Type Routines

The decimal structure has four parts:

dec_exp holds the exponent of the normalized DECIMAL-type num-ber. This exponent represents a power of 100.

dec_pos holds the sign of the DECIMAL-type number (1 when thenumber is zero or greater; 0 when less than zero).

dec_ndgts contains the number of base 100 significant digits of theDECIMAL-type number.

dec_dgts is a character array that holds the significant digits of thenormalized DECIMAL-type number (dec_dgts[0] != 0). Eachcharacter in the array is a one-byte binary number in base100. dec_ndgts contains the number of significant digits indec_dgts.

DECIMAL-Type RoutinesAll operations on DECIMAL-type numbers should take place through theroutines provided in the INFORMIX-4GL library and described in the follow-ing pages. Any other operations, modifications, or analysis of DECIMAL-typenumbers can produce unpredictable results.

The following C function calls are available in INFORMIX-4GL to treatDECIMAL-type numbers:

deccvasc( ) convert C char type to DECIMAL-typedectoasc( ) convert DECIMAL-type to C char typedeccvint( ) convert C int type to DECIMAL-typedectoint( ) convert DECIMAL-type to C int typedeccvlong( ) convert C long type to DECIMAL-typedectolong( ) convert DECIMAL-type to C long typedeccvflt( ) convert C float type to DECIMAL-typedectoflt( ) convert DECIMAL-type to C float typedeccvdbl( ) convert C double type to DECIMAL-typedectodbl( ) convert DECIMAL-type to C double typedecadd( ) add two decimal numbersdecsub( ) subtract two decimal numbersdecmul( ) multiply two decimal numbersdecdiv( ) divide two decimal numbersdeccmp( ) compare two decimal numbersdeccopy( ) copy a decimal numberdececvt( ) convert decimal value to ASCII string

(corresponds to ecvt(3) on UNIX systems)decfcvt( ) convert decimal value to ASCII string

(corresponds to fcvt(3) on UNIX systems)

F-2 DECIMAL Functions for C

Page 739: Manual Informix

DECCVASC

DECCVASC

OverviewUse deccvasc to convert a value held as a printable character in a C char typeinto a DECIMAL-type number.

Syntaxdeccvasc(cp, len, np)

char *cp;int len;dec_t *np;

Explanationcp points to a string that holds the value to be converted.

len is the length of the string.

np is a pointer to a dec_t structure to receive the result of the conversion.

Notes1. The deccvasc function ignores leading spaces in the character string.

2. The character string can have a leading plus (+) or minus (-) sign, a deci-mal point (.), and numbers to the right of the decimal point.

3. The character string can contain an exponent preceded by either e or E.The exponent can be preceded by a plus or minus sign.

Return Codes0 Function was successful.

-1200 Number is too large to fit into a DECIMAL-type (overflow).

-1201 Number is too small to fit into a DECIMAL-type (underflow).

-1213 String has non-numeric characters.

-1216 String has bad exponent.

DECIMAL Functions for C F-3

Page 740: Manual Informix

DECCVASC

Examples#include <decimal.h>

char input[80];dec_t number;

.

.

./* get input from terminal */getline(input);

/* convert input into decimal number */deccvasc(input, 32, &number);

F-4 DECIMAL Functions for C

Page 741: Manual Informix

DECTOASC

DECTOASC

OverviewUse dectoasc to convert a DECIMAL-type number to an ASCII string.

Syntaxdectoasc(np, cp, len, right)

dec_t *np;char *cp;int len;int right;

Explanationnp is a pointer to the decimal structure whose associated decimal value

you want to convert to an ASCII string.

cp is a pointer to the beginning of the character buffer to hold the ASCIIstring.

len is the maximum length in bytes of the string buffer.

right is an integer indicating the number of decimal places to the right ofthe decimal point.

Notes1. If right equals -1, the number of decimal places is determined by the dec-

imal value of *np.

2. If the number does not fit into a character string of length len, dectoascconverts the number to exponential notation. If the number still does notfit, dectoasc fills the string with asterisks. If the number is shorter than thestring, it is left-justified and padded on the right with blanks.

3. Because the ASCII string returned by dectoasc is not null-terminated,your program must add a null character to the string before printing it.

Return Codes0 Conversion was successful.

-1 Conversion was not successful.

DECIMAL Functions for C F-5

Page 742: Manual Informix

DECTOASC

Examples#include <decimal.h>

char input[80];char output[16];dec_t number;

.

.

.

/* get input from terminal */getline(input);

/* convert input into decimal number */deccvasc(input, 32, &number);

/* convert number to ASCII string */dectoasc(&number, output, 15, 1);

/* add null character to end of string prior to printing */output[15] = ’\0’;

/* print the value just entered */printf("You just entered %s", output);

F-6 DECIMAL Functions for C

Page 743: Manual Informix

DECCVINT

DECCVINT

OverviewUse deccvint to convert a C type int into a DECIMAL-type number.

Syntaxdeccvint(integer, np)

int integer;dec_t *np;

Explanationinteger is the integer you want to convert.

np is a pointer to a dec_t structure that receives the result of theconversion.

Examples#include <decimal.h>

dec_t decnum;

/* convert the integer value -999* into a DECIMAL-type number*/

deccvint(-999, &decnum);

DECIMAL Functions for C F-7

Page 744: Manual Informix

DECTOINT

DECTOINT

OverviewUse dectoint to convert a DECIMAL-type number into a C type int.

Syntaxdectoint(np, ip)

dec_t *np;int *ip;

Explanationnp is a pointer to a decimal structure whose value is converted to an

integer.

ip is a pointer to the integer.

Return Codes0 Conversion was successful.

-1200 The magnitude of the DECIMAL-type number > 32767.

Examples#include <decimal.h>

dec_t mydecimal;int myinteger;

/* convert the value in* mydecimal into an integer* and place the results in* the variable myinteger.*/

dectoint(&mydecimal, &myinteger);

F-8 DECIMAL Functions for C

Page 745: Manual Informix

DECCVLONG

DECCVLONG

OverviewUse deccvlong to convert a C type long value into a DECIMAL-type number.

Syntaxdeccvlong(lng, np)

long lng;dec_t *np;

Explanationlng is a pointer to a long integer.

np is a pointer to a dec_t structure that receives the result of theconversion.

Examples#include <decimal.h>

dec_t mydecimal;long mylong;

/* Set the decimal structure* mydecimal to 37.*/

deccvlong(37L, &mydecimal);

mylong = 123456L;/* Convert the variable mylong into

* a DECIMAL-type number held in* mydecimal.*/

deccvlong(mylong, &mydecimal);

DECIMAL Functions for C F-9

Page 746: Manual Informix

DECTOLONG

DECTOLONG

OverviewUse dectolong to convert a DECIMAL-type number into a C type long.

Syntaxdectolong(np, lngp)

dec_t *np;long *lngp;

Explanationnp is a pointer to a decimal structure.

lngp is a pointer to a long where the result of the conversion will beplaced.

Return Codes0 Conversion was successful.

-1200 The magnitude of the DECIMAL-type number > 2,147,483,647.

Examples#include <decimal.h>

dec_t mydecimal;long mylong;

/* convert the DECIMAL-type value* held in the decimal structure* mydecimal to a long pointed to* by mylong.*/

dectolong(&mydecimal, &mylong);

F-10 DECIMAL Functions for C

Page 747: Manual Informix

DECCVFLT

DECCVFLT

OverviewUse deccvflt to convert a C type float into a DECIMAL-type number.

Syntaxdeccvflt(flt, np)

float flt;dec_t *np;

Explanationflt is a floating-point number.

np is a pointer to a dec_t structure that receives the result of theconversion.

Examples#include <decimal.h>

dec_t mydecimal;float myfloat;

/* Set the decimal structure* myfloat to 3.14159.*/

deccvflt(3.14159, &mydecimal);

myfloat = 123456.78;

/* Convert the variable myfloat into* a DECIMAL-type number held in* mydecimal.*/

deccvflt(myfloat, &mydecimal);

DECIMAL Functions for C F-11

Page 748: Manual Informix

DECTOFLT

DECTOFLT

OverviewUse dectoflt to convert a DECIMAL-type number into a C type float.

Syntaxdectoflt(np, fltp)

dec_t *np;float *fltp;

Explanationnp is a pointer to a decimal structure.

fltp is a pointer to a floating-point number to receive the result of theconversion.

NotesThe resulting floating-point number has eight significant digits.

Examples#include <decimal.h>

dec_t mydecimal;float myfloat;

/* convert the DECIMAL-type value* held in the decimal structure* mydecimal to a floating point number pointed to* by myfloat.*/

dectoflt(&mydecimal, &myfloat);

F-12 DECIMAL Functions for C

Page 749: Manual Informix

DECCVDBL

DECCVDBL

OverviewUse deccvdbl to convert a C type double into a DECIMAL-type number.

Syntaxdeccvdbl(dbl, np)

double dbl;dec_t *np;

Explanationdbl is a double-precision, floating-point number.

np is a pointer to a dec_t structure that receives the result of theconversion.

Examples#include <decimal.h>

dec_t mydecimal;double mydouble;

/* Set the decimal structure* mydecimal to 3.14159.*/

deccvdbl(3.14159, &mydecimal);

mydouble = 123456.78;

/* Convert the variable mydouble into* a DECIMAL-type number held in* mydecimal.*/

deccvdbl(mydouble, &mydecimal);

DECIMAL Functions for C F-13

Page 750: Manual Informix

DECTODBL

DECTODBL

OverviewUse dectodbl to convert a DECIMAL-type number into a C type double.

Syntaxdectodbl(np, dblp)

dec_t *np;double *dblp;

Explanationnp is a pointer to a decimal structure.

dblp is a pointer to a double-precision, floating-point number thatreceives the result of the conversion.

NotesThe resulting double-precision number receives a total of 16 significantdigits.

Examples#include <decimal.h>

dec_t mydecimal;double mydouble;

/* convert the DECIMAL-type value* held in the decimal structure* mydecimal to a double pointed to* by mydouble.*/

dectodbl(&mydecimal, &mydouble);

F-14 DECIMAL Functions for C

Page 751: Manual Informix

DECADD, DECSUB, DECMUL, and DECDIV

DECADD, DECSUB, DECMUL, and DECDIV

OverviewThe decimal arithmetic routines take pointers to three decimal structures asparameters. The first two decimal structures hold the operands of the arith-metic function. The third decimal structure holds the result.

Syntaxdecadd(n1, n2, result) /* result = n1 + n2 */

dec_t *n1;dec_t *n2;dec_t *result;

decsub(n1, n2, result) /* result = n1 - n2 */dec_t *n1;dec_t *n2;dec_t *result;

decmul(n1, n2, result) /* result = n1 * n2 */dec_t *n1;dec_t *n2;dec_t *result;

decdiv(n1, n2, result) /* result = n1 / n2 */dec_t *n1;dec_t *n2;dec_t *result;

Explanationn1 is a pointer to the decimal structure of the first operand.

n2 is a pointer to the decimal structure of the second operand.

result is a pointer to the decimal structure of the result of the operation.

NotesThe result can use the same pointer as either n1 or n2.

DECIMAL Functions for C F-15

Page 752: Manual Informix

DECADD, DECSUB, DECMUL, and DECDIV

Return Codes0 Operation was successful.

-1200 Operation resulted in overflow.

-1201 Operation resulted in underflow.

-1202 Operation attempts to divide by zero.

F-16 DECIMAL Functions for C

Page 753: Manual Informix

DECCMP

DECCMP

OverviewUse deccmp to compare two DECIMAL-type numbers.

Syntaxint deccmp(n1, n2)

dec_t *n1;dec_t *n2;

Explanationn1 is a pointer to the decimal structure of the first number.

n2 is a pointer to the decimal structure of the second number.

Return Codes0 The two values are the same.

-1 The first value is less than the second.

+1 The first value is greater than the second.

DECIMAL Functions for C F-17

Page 754: Manual Informix

DECCOPY

DECCOPY

OverviewUse deccopy to copy one dec_t structure to another.

Syntaxdeccopy(n1, n2)

dec_t *n1;dec_t *n2;

Explanationn1 is a pointer to the source dec_t structure.

n2 is a pointer to the destination dec_t structure.

F-18 DECIMAL Functions for C

Page 755: Manual Informix

DECECVT and DECFCVT

DECECVT and DECFCVT

OverviewThese functions convert a DECIMAL value to an ASCII string.

Syntaxchar *dececvt(np, ndigit, decpt, sign)

dec_t *np;int ndigit;int *decpt;int *sign;

char *decfcvt(np, ndigit, decpt, sign)dec_t *np;int ndigit;int *decpt;int *sign;

Explanationnp is a pointer to a dec_t structure that contains the number you want to

convert.

ndigit is, for dececvt, the length of the ASCII string; for decfcvt, it is thenumber of digits to the right of the decimal point.

decpt points to an integer that is the position of the decimal point relativeto the beginning of the string. A negative value for *decpt means tothe left of the returned digits.

sign is a pointer to the sign of the result. If the sign of the result is negative,*sign is nonzero; otherwise, the value is zero.

Notes1. The dececvt function converts the decimal value pointed to by np into a

null-terminated string of ndigit ASCII digits, and returns a pointer to thestring.

2. The low-order digit of the DECIMAL number is rounded.

3. The decfcvt function is identical to dececvt, except that ndigit specifies thenumber of digits to the right of the decimal point instead of the total num-ber of digits.

DECIMAL Functions for C F-19

Page 756: Manual Informix

DECECVT and DECFCVT

ExamplesIn the following example, np points to a dec_t structure containing 12345.67and *decpt points to an integer containing a 5:

ptr = dececvt (np,4,&decpt,&sign); = 1235ptr = dececvt (np,10,&decpt,&sign); = 1234567000ptr = decfcvt (np,1,&decpt,&sign); = 123457ptr = decfcvt (np,3,&decpt,&sign); = 12345670

In this example, np points to a dec_t structure containing a 0.001234 and*decpt points to an integer containing a -2:

ptr = dececvt (np,4,&decpt,&sign); = 1234ptr = dececvt (np,10,&decpt,&sign); = 1234000000ptr = decfcvt (np,1,&decpt,&sign); =ptr = decfcvt (np,3,&decpt,&sign); = 1

F-20 DECIMAL Functions for C

Page 757: Manual Informix

Appendix

G

Outer JoinsThis appendix discusses the difference between a simplejoin and an outer join, and describes in detail how outerjoins work. The following SELECT statements illustrate thebasic difference between the two types of join.

SELECT customer.customer_num, lname, order_numFROM customer, ordersWHERE customer.customer_num = orders.customer_num

Figure G-1 Query 1. Using a Simple Join

SELECT customer.customer_num, lname, order_numFROM customer, OUTER ordersWHERE customer.customer_num = orders.customer_num

Figure G-2 Query 2. Using an Outer Join

Both query the same tables (customer and orders) of thesame database (stores) through a join on the same column(customer_num). At first glance, both fetch the same data.The query results, however, are quite different, as the fol-lowing illustration shows.

Page 758: Manual Informix

How Outer Joins Work

customer_num lname order_num customer_num lname order_num

104 Higgins 1001 101 Pauli 1002101 Pauli 1002 102 Sadler104 Higgins 1003 103 Currie106 Watson 1004 104 Higgins 1001116 Parmelee 1005 104 Higgins 1003112 Lawson 1006 104 Higgins 1011117 Sipes 1007 104 Higgins 1013110 Jaeger 1008 105 Vector111 Keyes 1009 106 Watson 1004115 Grant 1010 106 Watson 1014104 Higgins 1011 107 Ream117 Sipes 1012 108 Quinn104 Higgins 1013 109 Miller106 Watson 1014 110 Jaeger 1008110 Jaeger 1015 110 Jaeger 1015

111 Keyes 1009112 Lawson 1006113 Beatty114 Albertson115 Grant 1010116 Parmelee 1005117 Sipes 1007117 Sipes 1012118 Baxter

Figure G-3 Query 1 Results Query 2 Results

By using a simple join, Query 1 fetches a list of only those customers who haveitems on order, while Query 2 fetches a list of all customers by using an outerjoin. Once you understand how similar queries can produce such dissimilarresults, you can begin to use outer joins effectively. The obvious differencesbetween the two kinds of joins are as follows:

• A simple join discards all rows that do not satisfy the join condition.

• An outer join preserves rows that would otherwise be discarded.

The following section discusses outer joins in detail.

How Outer Joins WorkA join queries two or more tables as though they were one. It is as if 4GL cre-ates and then acts upon a single temporary table to produce the query results.4GL does not actually create such a table to perform a join, but it is helpful toconceptualize a join in these terms.

In a simple two-table join, the resulting ‘‘table’’ contains only those combina-tions of rows from both tables that satisfy the join condition. In an outer join,the resulting ‘‘table’’ contains these rows, plus all remaining rows from oneof the tables, called the dominant (or preserved) table. The second table iscalled the subservient table.

G-2 Outer Joins

Page 759: Manual Informix

How Outer Joins Work

Consider two hypothetical tables, employees and depts, which contain thefollowing columns and rows (dash ‘‘—’’ indicates a NULL value):

employees depts

emp_num dept_num dept_num dept_loc2 105 102 NY4 103 103 LA6 103 105 SF5 —3 102

Suppose, for example, that you need a list of employee numbers and depart-ment locations for all employees, including those employees whose depart-ment locations are unknown (represented by NULL values in the employeestable). The following query fetches the desired results:

SELECT emp_num, dept_locFROM employees, OUTER deptsWHERE employees.dept_num = depts.dept_num

The keyword OUTER designates depts as the subservient table, makingemployees the dominant table. 4GL processes the query by the followingsteps:

1. 4GL applies filters to the subservient table while sequentially applyingthe join condition to the rows of the dominant table. Rows in the domi-nant table are retrieved without considering the join, but rows from thesubservient table (outer table) are retrieved only if they satisfy the joincondition. Any dominant-table rows that do not have a matching rowfrom the subservient table receive a row of NULL values in place of a sub-servient-table row.

The result is a ‘‘table’’ with the following rows:

emp_num dept_num dept_num dept_loc2 105 105 SF3 102 102 NY4 103 103 LA5 — — —6 103 103 LA

Note: A filter is a condition expressed in a WHERE clause that applies to col-umns in a single table. For example,

"dept_loc = SF" or "emp_num < 105"

Because 4GL applies such filters to the subservient table as it performs the join,the resulting ‘‘table’’ may contain NULL values that were not present in the sub-servient table prior to the join.

Outer Joins G-3

Page 760: Manual Informix

How Outer Joins Work

Suppose that the query includes a filter on the dept_loc column:

SELECT emp_num, dept_locFROM employees, OUTER deptsWHERE employees.dept_num = depts.dept_num

AND dept_loc != "LA"

At Step 2, the results include more rows of NULL values than the results of theoriginal query:

emp_num dept_num dept_num dept_loc2 105 105 SF3 102 102 NY4 — — —5 — — —6 — — —

The filter removes rows from the depts table where dept_loc is equal to LA.

2. After performing the join, 4GL applies filters to the dominant table (if theyexist).

3. 4GL applies the SELECT clause to eliminate unneeded columns, and thequery returns the results.

emp_num dept_loc2 SF3 NY4 LA5 —6 LA

In a similar way to the previous example, the following query produces alist of all customers with supplemental information for those customerswith items on order. Where orders.customer_num is not equal to

G-4 Outer Joins

Page 761: Manual Informix

How Outer Joins Work

customer.customer_num, 4GL combines a row of NULL values with the cor-responding row from the customer table. Because the query does not containfilters, the results preserve every row from the dominant table.

SELECT customer.customer_num, company, order_num, ship_dateFROM customer, OUTER ordersWHERE customer.customer_num = orders.customer_num

Figure G-4 Query 3

customer_num company order_num ship_date

101 All Sports Supplies 1002 06/06/1984102 Sports Spot103 Phil’s Sports104 Play Ball! 1001 06/05/1984104 Play Ball! 1003 06/07/1984104 Play Ball! 1011 06/07/1984104 Play Ball! 1013 06/11/1984105 Los Altos Sports106 Watson & Son 1004106 Watson & Son 1014 06/09/1984107 Athletic Supplies108 Quinn’s Sports109 Sport Stuff110 AA Athletics 1008 06/27/1984110 AA Athletics 1015 06/11/1984111 Sports Center 1009 06/15/1984112 Runners & Others 1006113 Sportstown114 Sporting Place115 Gold Medal Sports 1010 06/07/1984116 Olympic City 1005 06/08/1984117 Kids Korner 1007 06/08/1984117 Kids Korner 1012 06/09/1984118 Blue Ribbon Sports

Figure G-5 Query 3 Results

The preceding example queries two tables in the simplest type of outer join.You can, in fact, use outer joins to query any number of tables, producingmore types of joins than can be discussed here. The following types are pos-sible when three tables are involved in a query:

• You can outer-join the result of a simple join to a third table.

SELECT column-listFROM x, OUTER (y,z)WHERE x.a = y.a AND y.b = z.b

Query 4 performs this kind of join. (See the section “Examples” later inthis chapter.)

Outer Joins G-5

Page 762: Manual Informix

Examples

• You can outer-join the result of an outer join to a third table.

SELECT column-listFROM x, OUTER (y, OUTER z)WHERE x.a = y.a AND y.b = z.b

or

SELECT column-listFROM x, OUTER (y, OUTER z)WHERE x.a = z.a AND y.b = z.b

Queries 5 and 6 perform this kind of join. (See the following ‘‘Examples’’section.)

• You can outer-join two tables individually to a third table, in which case,join relationships are possible only between the subservient tables andthe dominant table. Query 7 performs this kind of join. (See the following‘‘Examples’’ section.)

SELECT column-listFROM x, OUTER y, OUTER zWHERE x.a = y.a AND x.b = z.b

When you outer-join several tables to another table, make sure that yourWHERE clause does not specify impossible join conditions. The followingquery attempts a join between two subservient tables:

SELECT column-listFROM x, OUTER y, OUTER zWHERE x.a = y.a AND y.b = z.b

An error results; every outer join must have a dominant table.

The following examples use the stores database to demonstrate commonmulti-table outer joins.

ExamplesThis query outer-joins the result of a simple join to a third table. It producesa list of all customers with supplemental information (order number, stocknumber, manufacturer code, and quantity ordered) for those customers whohave ordered items manufactured by Anza.

SELECT customer.customer_num, lname,orders.order_num, stock_num, manu_code, quantity

FROM customer, OUTER (orders, items)WHERE customer.customer_num = orders.customer_num ANDorders.order_num = items.order_num ANDmanu_code = "ANZ"

Figure G-6 Query 4

G-6 Outer Joins

Page 763: Manual Informix

Examples

4GL performs the simple join between orders and items first, yielding infor-mation on all orders for Anza-manufactured items. The outer join combinesthe customer table with the Anza order information. The query results do notinclude orders for other items.

customer_num lname order_num stock_num manu_code quantity

101 Pauli102 Sadler103 Currie104 Higgins 1003 9 ANZ 1104 Higgins 1003 8 ANZ 1104 Higgins 1003 5 ANZ 5104 Higgins 1011 5 ANZ 5104 Higgins 1013 5 ANZ 1104 Higgins 1013 6 ANZ 1104 Higgins 1013 9 ANZ 2105 Vector106 Watson107 Ream108 Quinn109 Miller110 Jaeger 1008 8 ANZ 1110 Jaeger 1008 9 ANZ 5111 Keyes112 Lawson 1006 5 ANZ 5112 Lawson 1006 6 ANZ 1113 Beatty114 Albertson115 Grant 1010 6 ANZ 1116 Parmelee 1005 5 ANZ 10116 Parmelee 1005 6 ANZ 1117 Sipes 1012 8 ANZ 1117 Sipes 1012 9 ANZ 10118 Baxter

Figure G-7 Query 4 Results

Query 5This query outer-joins the result of an outer join to a third table. When youuse a nested outer join, the query preserves order numbers that Query 4(using a nested simple join) eliminates. The query results include all orders,whether or not they contain Anza-manufactured items. For other items, thecondition

where manu_code = "ANZ"

Outer Joins G-7

Page 764: Manual Informix

Examples

eliminates stock numbers, manufacturer codes, and quantities as before.

SELECT customer.customer_num, lname,orders.order_num, stock_num, manu_code, quantity

FROM customer, OUTER (orders, OUTER items)WHERE customer.customer_num = orders.customer_num ANDorders.order_num = items.order_num ANDmanu_code = "ANZ"

customer_num lname order_num stock_num manu_code quantity

101 Pauli 1002102 Sadler103 Currie104 Higgins 1001104 Higgins 1003 9 ANZ 1104 Higgins 1003 8 ANZ 1104 Higgins 1003 5 ANZ 5104 Higgins 1011 5 ANZ 5104 Higgins 1013 5 ANZ 1104 Higgins 1013 6 ANZ 1104 Higgins 1013 9 ANZ 2105 Vector106 Watson 1004106 Watson 1014107 Ream108 Quinn109 Miller110 Jaeger 1008 8 ANZ 1110 Jaeger 1008 9 ANZ 5110 Jaeger 1015111 Keyes 1009112 Lawson 1006 5 ANZ 5112 Lawson 1006 6 ANZ 1113 Beatty114 Albertson115 Grant 1010 6 ANZ 1116 Parmelee 1005 5 ANZ 10116 Parmelee 1005 6 ANZ 1117 Sipes 1007117 Sipes 1012 8 ANZ 1117 Sipes 1012 9 ANZ 10118 Baxter

Figure G-8 Query 5 Results

In addition to customer, orders, and so on, the following queries include ahypothetical table named custnotes, containing the following columns anddata:

customer_num notes104 sponsors soccer team108 customer for 20 years115 opening a second store118 new customer

G-8 Outer Joins

Page 765: Manual Informix

Examples

Query 6

This query produces a list of all customers with order numbers and selectednotes.

SELECT customer.customer_num, orders.order_num, notesFROM customer, OUTER (orders, OUTER custnotes)WHERE customer.customer_num = orders.customer_num ANDorders.customer_num = custnotes.customer_num

The outer join between custnotes and orders preserves notes only for cus-tomers who also have orders.

customer_num order_num notes

101 1002102103104 1001 sponsors soccer team104 1003 sponsors soccer team104 1011 sponsors soccer team104 1013 sponsors soccer team105106 1004106 1014107108109110 1008110 1015111 1009112 1006113114115 1010 opening a second store116 1005117 1007117 1012118

Figure G-9 Query 6 Results

To preserve notes for customers 108 and 118 who do not have orders, youmust outer-join the custnotes table directly with the customer table, as shownin the next query.

Query 7

This query outer-joins two tables individually to a third table. It outer-joinsboth orders and custnotes to customer (the dominant table).

SELECT customer.customer_num, orders.order_num, notesFROM customer, OUTER orders, OUTER custnotesWHERE customer.customer_num = orders.customer_num ANDcustomer.customer_num = custnotes.customer_num

Outer Joins G-9

Page 766: Manual Informix

Examples

Customer notes now appear, regardless of whether customers have orders.

customer_num order_num notes

101 1002102103104 1001 sponsors soccer team104 1003 sponsors soccer team104 1011 sponsors soccer team104 1013 sponsors soccer team105106 1004106 1014107108 customer for 20 years109110 1008110 1015 opening a second store111 1009112 1006113114115 1010116 1005117 1007117 1012118 new customer

Figure G-10 Query 7 Results

All of the preceding queries fetch information from one table with supple-mental information from other tables. When you need similar results, Infor-mix recommends that you use an outer join. When you do not needsupplemental information, as is normally the case, use a simple join instead.

Be aware that your choice of an outer join can influence query optimizationand processing. You can use the SET EXPLAIN ON statement to examine howthe query processor of INFORMIX-4GL performs simple queries, joins, andouter joins.

G-10 Outer Joins

Page 767: Manual Informix

Appendix

H

ASCII Character Set

Page 768: Manual Informix

Num Char Num Char Num Char0 ^@ 43 + 86 V1 ^A 44 , 87 W2 ^B 45 - 88 X3 ^C 46 . 89 Y4 ^D 47 / 90 Z5 ^E 48 0 91 [6 ^F 49 1 92 \7 ^G 50 2 93 ]8 ^H 51 3 94 ^9 ^I 52 4 95 _10 ^J 53 5 96 `11 ^K 54 6 97 a12 ^L 55 7 98 b13 ^M 56 8 99 c14 ^N 57 9 100 d15 ^O 58 : 101 e16 ^P 59 ; 102 f17 ^Q 60 < 103 g18 ^R 61 = 104 h19 ^S 62 > 105 i20 ^T 63 ? 106 j21 ^U 64 @ 107 k22 ^V 65 A 108 l23 ^W 66 B 109 m24 ^X 67 C 110 n25 ^Y 68 D 111 o26 ^Z 69 E 112 p27 esc 70 F 113 q28 ^\ 71 G 114 r29 ^] 72 H 115 s30 ^^ 73 I 116 t31 ^_ 74 J 117 u32 75 K 118 v33 ! 76 L 119 w34 " 77 M 120 x35 # 78 N 121 y36 $ 79 O 122 z37 % 80 P 123 {38 & 81 Q 124 |39 ’ 82 R 125 }40 ( 83 S 126 ~41 ) 84 T 127 del42 * 85 U

^x = CONTROL-X

H-2 ASCII Character Set

Page 769: Manual Informix

Appendix

I

Modifying termcapand terminfoINFORMIX-4GL programs can use function keys and candisplay color or intensity attributes in screen displays.These and other keyboard and screen options are terminaldependent. To determine terminal-dependent characteris-tics, INFORMIX-4GL uses the information in the termcapfile or in the terminfo directory. INFORMIX-4GL uses theINFORMIXTERM environment variable to determinewhether to use termcap or terminfo. For more informationabout INFORMIXTERM, read the discussion of environmentvariables in the ‘‘Environment Variables’’ appendix or inthe Preface to the INFORMIX-4GL User Guide .

With INFORMIX-4GL, Informix distributes termcap filesthat contain additional capabilities for many common ter-minals (such as the Wyse 50 and the Televideo 950). Thesecapabilities include intensity-change or color-changedescriptions or both. This appendix describes these capabil-ities, as well as the general format of termcap and terminfoentries.

Since terminfo does not support color, you can only useINFORMIX-4GL color functionality with termcap. If youwant to use color in INFORMIX-4GL, you must set theINFORMIXTERM environment variable to termcap.

You can use the information in this appendix, combinedwith the information in your terminal manual, to modifythe contents of your termcap file or terminfo files. Thisappendix is divided into two main sections, termcap andterminfo. Depending on which you are using, you shouldread the appropriate section.

Page 770: Manual Informix

termcap

termcapWhen INFORMIX-4GL is installed on your system, a termcap file is placed inthe etc subdirectory of $INFORMIXDIR. This file is a superset of an operatingsystem termcap file. The Informix termcap file contains additional capabili-ties for many terminals. You may want to modify this file further in the fol-lowing instances:

• The entry for your terminal has not been modified to include color-change and intensity-change capabilities.

• You want to extend function key definitions.

• You want to specify or alter the graphics characters used for windowborders.

• You want to customize your terminal entry in other ways.

Note: Some terminals cannot support color or graphics characters. You should readthis appendix and the user guide that comes with your terminal to determine whetheror not the changes described in this appendix are applicable to your terminal.

Format of a termcap DefinitionThis section describes the general format of termcap entries. For a completedescription of termcap, refer to your operating system documentation.

A termcap entry contains a list of names for the terminal, followed by a listof the terminal’s capabilities. There are three types of capabilities:

• Boolean capabilities

• Numeric capabilities

• String capabilities

All termcap entries have the following format:

• ESCAPE is specified as a backslash ( \ ) followed by the letter E, and CTRLis specified as a caret (^). Do not use the ESCAPE or CTRL keys to indicateescape sequences or control characters in a termcap entry.

• Each capability, including the last one in the entry, is followed by acolon ( : ).

• Entries must be defined on a single logical line; a backslash ( \ ) appearsat the end of each line that wraps to the next line.

I-2 Modifying termcap and terminfo

Page 771: Manual Informix

Format of a termcap Definition

Figure I-1 shows a basic termcap entry for the Wyse 50 terminal:

# Entry for Wyse 50:

w5|wy50|wyse50::if=/usr/lib/tabset/std:\:al=\EE:am:bs:ce=\Et:cm=\E=%+ %+ :cl=\E*:co#80:\:dc=\EW:dl=\ER:ho=^^:ei=:kh=^^:im=:ic=\EQ:in:li#24:\:nd=^L:pt:se=\EG0:so=\EG4:sg#1:ug#1:\:up=^K:ku=^K:kd=^J:kl=^H:kr=^L:kb=:\:k0=^A@^M:k1=^AA^M:k2=^AB^M:k3=^AC^M:k4=^AD^M:\:k5=^AE^M:k6=^AF^M:k7=^AG^M:\:HI=^|:Po=^R:Pe=^T:

Figure I-1 Wyse 50 termcap Entry

Note: Comment lines begin with a pound sign ( # ).

Terminal Names

A termcap entry starts with one or more names for the terminal, each sepa-rated by a vertical ( | ) bar. For example, the termcap entry for the Wyse 50terminal starts with the following line:

w5|wy50|wyse50:\

The termcap entry can be accessed using any one of these names.

Boolean Capabilities

A Boolean capability is a two-character code that indicates whether or not aterminal has a specific feature. If the Boolean capability is present in the ter-mcap entry, the terminal has that particular feature. Figure I-2 shows some ofthe Boolean capabilities for the Wyse 50 terminal:

:bs:am:

# bs backspace with CTRL-H# am automatic margins

Figure I-2 Boolean Capabilities for the Wyse 50

Modifying termcap and terminfo I-3

Page 772: Manual Informix

Format of a termcap Definition

Numeric Capabilities

A numeric capability is a two-character code followed by a pound symbol( # ) and a value. Figure I-3 shows the numeric capabilities for the number ofcolumns and the number of lines on a Wyse 50 terminal:

:co#80:li#24:

# co number of columns in a line# li number of lines on the screen

Figure I-3 Numeric Capabilities for the Wyse 50

Similarly, sg is a numeric capability that indicates the number of characterpositions required on the screen for reverse video. The entry :sg#1: indi-cates that a terminal requires one additional character position when reversevideo is turned ON or OFF. If you do not include a particular numeric capa-bility, INFORMIX-4GL assumes that the value is zero.

String Capabilities

A string capability specifies a sequence that can be used to perform a terminaloperation. A string capability is a two-character code followed by an equalsign ( = ) and a string ending at the next delimiter ( : ).

Most termcap entries include string capabilities for clearing the screen, cur-sor movement, Arrow keys, underscore, function keys, and so on. Figure I-4shows many of the string capabilities for the Wyse 50 terminal:

:ce=\Et:cl=\E*:\:nd=^L:up=^K:\:so=\EG4:se=\EG0:\:ku=^K:kd=^J:kr=^L:kl=^H:\:k0=^A@^M:k1=^AA^M:k2=^AB^M:k3=^AC^M:

# ce=\Et clear to end of line# cl=\E* clear the screen# nd=^L non-destructive cursor right# up=^K up one line## so=\EG4 start stand-out# se=\EG0 end stand-out#

I-4 Modifying termcap and terminfo

Page 773: Manual Informix

Extending Function Key Definitions

# ku=^K up arrow key# kd=^J down arrow key# kr=^L right arrow key# kl=^H left arrow key## k0=^A@^M function key F1# k1=^AA^M function key F2# k2=^AB^M function key F3# k3=^AC^M function key F4

Figure I-4 String Capabilities for the Wyse 50

Extending Function Key DefinitionsINFORMIX-4GL recognizes function keys F1 through F36. These keys corre-spond to the termcap capabilities k0 through k9, followed by kA through kZ.The termcap entry for these capabilities is the sequence of ASCII charactersyour terminal sends when you press the function keys (or any other keys youchoose to use as function keys). For the Wyse 50 and Televideo 950 terminals,the first eight function keys send the characters shown in Figure I-5.

Function Key termcap EntryF1 k0=^A@^MF2 k1=^AA^MF3 k2=^AB^MF4 k3=^AC^MF5 k4=^AD^MF6 k5=^AE^MF7 k6=^AF^MF8 k7=^AG^M

Figure I-5 Function Key Entries for the Wyse 50

You can also define keys that correspond to the following capabilities:

• Insert line (ki)

• Delete line (kj)

• Next page (kf)

• Previous page (kg)

If these keys are defined in your termcap file, INFORMIX-4GL uses them.Otherwise, INFORMIX-4GL uses CTRL-J, CTRL-K, CTRL-M, and CTRL-N,respectively.

Note: You can also use the OPTIONS statement to name other function keys orCTRL keys for these operations.

Modifying termcap and terminfo I-5

Page 774: Manual Informix

Specifying Characters for Window Borders

Specifying Characters for Window BordersINFORMIX-4GL uses characters defined in the termcap file to draw the bor-der of a window. If no characters are defined in this file, INFORMIX-4GL usesthe hyphen ( - ) for horizontal lines, the vertical bar ( | ) for vertical lines, andthe plus sign ( + ) for corners.

The termcap file provided with INFORMIX-4GL contains border characterdefinitions for many common terminals. You can look at the termcap file tosee if the entry for your terminal has been modified to include these defini-tions. If your terminal entry does not contain border character definitions, orif you want to specify alternative border characters, you or your systemadministrator can modify the termcap file.

Perform the following steps to modify the definition for your terminal typein the termcap file:

1. Determine the escape sequences for turning graphics mode ON and OFF.This information is located in the manual that comes with your terminal.For example, on Wyse 50 terminals, the escape sequence for enteringgraphics mode is ESC H^B and the escape sequence for leaving graphicsmode is ESC H^C.

Note: Terminals without a graphics mode do not have this escape sequence. Theprocedure for specifying alternative border characters on a non-graphics terminalis discussed at the end of this section.

2. Identify the ASCII equivalents for the six graphics characters that INFOR-MIX-4GL requires to draw the border. (The ASCII equivalent of a graphicscharacter is the key you would press in graphics mode to obtain the indi-cated character.)

Figure I-6 shows the graphics characters and the ASCII equivalents for aWyse 50 terminal.

Window Border Graphics ASCIIPosition Character Equivalentupper left corner 2lower left corner 1upper right corner 3lower right corner 5horizontal - zvertical | 6

Figure I-6 Wyse 50 ASCII Equivalents for Border Graphics Characters

Again, this information should be located in the manual that comes withyour terminal.

3. Edit the termcap entry for your terminal.

I-6 Modifying termcap and terminfo

Page 775: Manual Informix

Specifying Characters for Window Borders

Note: You may want to make a copy of your termcap file before you edit it. Youcan use the TERMCAP environment variable to point to whichever copy of thetermcap file you want to access.

Use the format

termcap-capability=valueto enter values for the following termcap capabilities:

gs The escape sequence for entering graphics mode. In the termcapfile, ESCAPE is represented as a backslash ( \ ) followed by the let-ter E; CTRL is represented as a caret ( ^ ). For example, the Wyse50 escape sequence ESC-H CTRL-B is represented as \EH^B.

ge The escape sequence for leaving graphics mode. For example, theWyse 50 escape sequence ESC-H CTRL-C is represented as \EH^C.

gb The concatenated, ordered list of ASCII equivalents for the sixgraphics characters used to draw the border. Use the followingorder:

upper left cornerlower left cornerupper right cornerlower right cornerhorizontal linesvertical lines

Follow these guidelines when you insert information in the termcapentry:

1. Delimit entries with a colon ( : ).

2. End each continuing line with a backslash ( \ ).

3. End the last line in the entry with a colon.

For example, if you are using a Wyse 50 terminal, you would add the follow-ing information in the termcap entry for the Wyse 50:

:gs=\EH^B:\ # sets gs to ESC H CTRL B:ge=\EH^C:\ # sets ge to ESC H CTRL C:gb=2135z6:\ # sets gb to the ASCII equivalents

# of graphics characters for upper# left, lower left, upper right,# lower right, horizontal,# and vertical

If you prefer, you can enter this information in a linear sequence.

:gs=\EH^B:ge=\EH^C:gb=2135z6:\

Modifying termcap and terminfo I-7

Page 776: Manual Informix

Adding Color and Intensity

Terminals Without Graphics Capabilities

For terminals without graphics capabilities, you must enter a blank valuefor the gs and ge capabilities. For gb, enter the characters you want INFOR-MIX-4GL to use for the window border.

The following example shows possible values for gs, ge, and gb in an entryfor a terminal without graphics capabilities. In this example, window borderswould be drawn using underscores ( _ ) for horizontal lines, vertical bars ( | )for vertical lines, periods ( . ) for the top corners, and vertical bars ( | ) for thelower corners.

:gs=:ge=:gb=.|.|_|:

INFORMIX-4GL uses the graphics characters in the termcap file when youspecify a window border in an OPEN WINDOW statement.

Adding Color and IntensityMany of the terminal entries in the Informix termcap file (in the etc subdirec-tory of $INFORMIXDIR) have been modified to include color or intensitycapabilities or both. You can view the termcap file to determine if the entryfor your terminal type includes these capabilities. If your terminal entryincludes the ZA capability, your terminal is set up for color or intensity orboth. If it doesn’t, you can add color and intensity capabilities by using theinformation in this section. The following topics are outlined in this section:

• Color and intensity

• The ZA capability

• Stack operations

• Examples

You should understand these topics before you modify your terminal entry.

Color and Intensity Attributes

You can write your INFORMIX-4GL program either for a monochrome or acolor terminal and then run the program on either type of terminal. If you setup the termcap files as described here, the color attributes and the intensityattributes are related, as shown in Figure I-7.

I-8 Modifying termcap and terminfo

Page 777: Manual Informix

Adding Color and Intensity

Number Color Terminal Monochrome Terminal0 WHITE NORMAL1 YELLOW BOLD2 MAGENTA BOLD3 RED BOLD†4 CYAN DIM5 GREEN DIM6 BLUE DIM†7 BLACK INVISIBLE

Figure I-7 Color-Monochrome Correspondence

The background for colors is BLACK in all cases. In the Figure I-7, the † signi-fies that, if the keyword BOLD is indicated as the attribute, the field will beRED 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 change the color names from the default list by associating differentnumbers with different color names in a file named colornames in your cur-rent directory or in the /incl subdirectory of $INFORMIXDIR. (See the section“The colornames File” later in this appendix.)

In either color or monochrome mode, you can add the REVERSE, BLINK, orUNDERLINE attributes if your terminal supports them. You can select onlyone of these three attributes.

The ZA String Capability

INFORMIX-4GL uses a parameterized string capability ZA in the termcap fileto determine color assignments. Unlike other termcap string capabilities thatyou set equal to a literal sequence of ASCII characters, ZA is a function stringthat depends upon four parameters:

Parameter 1 (p1) Color number between 0 and 7 (see Figure I-7)Parameter 2 (p2) 0 = Normal; 1 = ReverseParameter 3 (p3) 0 = No-Blink; 1 = BlinkParameter 4 (p4) 0 = No-Underscore; 1 = Underscore

ZA uses the values of these four parameters and a stack machine to deter-mine which characters to send to the terminal. The ZA function is called andthese parameters are evaluated when a color or intensity attribute is encoun-tered in a 4GL program. You can use the information in your terminal manualto set the ZA parameters to the correct values for your terminal.

To define the ZA string for your terminal, you use stack operators to push andpop values onto and off the stack. The next section describes several stackoperators. Use these descriptions and the subsequent examples to under-stand how to define the string for your terminal.

Modifying termcap and terminfo I-9

Page 778: Manual Informix

Adding Color and Intensity

Stack Operations

The ZA string uses stack operations to either push values onto the stack orpop values off the stack. Typically, the instructions in the ZA string push aparameter onto the stack, compare it to one or more constants, and then sendan appropriate sequence of characters to the terminal. More complex opera-tions are often necessary and, by storing the display attributes in static stackmachine registers (named a through z), you can achieve terminal-specificoptimizations.

A summary follows of the different stack operators you can use to write thedescriptions. For a complete discussion of stack operators, consult your oper-ating system documentation.

Operators That Send Characters to the Terminal

%d pops a numeric value from the stack and sends a maximum ofthree digits to the terminal. For example, if the value 145 is at thetop of the stack, %d pops the value off the stack and sends theASCII representations of 1, 4, and 5 to the terminal. If the value2005 is at the top of the stack, %d pops the value off the stack andsends the ASCII representation of 5 to the terminal.

%2d pops a numeric value from the stack and sends a maximum of twodigits to the terminal, padding to two places. For example, if thevalue 145 is at the top of the stack, %2d pops the value off thestack and sends the ASCII representations of 4 and 5 to the termi-nal. If the value 5 is at the top of the stack, %2d pops the value offthe stack and sends the ASCII representations of 0 and 5 to theterminal.

%3d pops a numeric value from the stack and sends a maximum ofthree digits to the terminal, padding to three places. For example,if the value 7 is at the top of the stack, %3d pops the value off thestack and sends the ASCII representations of 0, 0, and 7 to theterminal.

%c pops a single character from the stack and sends it to the terminal.

Operators That Manipulate the Stack%p[1-9] pushes the value of the specified parameter on the stack. The

notation for parameters is p1, p2, ... p9. For example, if the valueof p1 is 3, %p1 pushes 3 on the stack.

%P[a-z] pops a value from the stack and stores it in the specified vari-able. The notation for variables is Pa, Pb, ... Pz. For example, if

I-10 Modifying termcap and terminfo

Page 779: Manual Informix

Adding Color and Intensity

the value 45 is on the top of the stack, %Pb pops 45 from thestack and stores it in the variable Pb.

%g[a-z] gets the value stored in the corresponding variable (P[a-z]) andpushes it on the stack. For example, if the value 45 is stored inthe variable Pb, %gb gets 45 from Pb and pushes it on the stack.

%´c´ pushes a single character on the stack. For example, %´k´pushes k on the stack.

%{n} pushes an integer constant on the stack. The integer can be anylength and can be either positive or negative. For example,%{0} pushes the value 0 on the stack.

%S[a-z] pops a value from the stack and stores it in the specified staticvariable. (Static storage is nonvolatile since the stored valueremains from one attribute evaluation to the next.) The notationfor static variables is Sa, Sb, ... Sz. For example, if the value 45 ison the top of the stack, %Sb pops 45 from the stack and stores itin the static variable Sb. This value is accessible for the durationof the INFORMIX-4GL program.

%G[a-z] gets the value stored in the corresponding static variable (S[a-z])and pushes it on the stack. For example, if the value 45 is storedin the variable Sb, %Gb gets 45 from Sb and pushes it on thestack.

Arithmetic Operators

Each arithmetic operator pops the top two values from the stack, performs anoperation, and pushes the result on the stack.

%+ Addition. For example, %{2}%{3}%+ is equivalent to 2+3.

%- Subtraction. For example, %{7}%{3}%- is equivalent to 7-3.

%* Multiplication. For example, %{6}%{3}%* is equivalent to 6*3.

%/ Integer division. For example, %{7}%{3}%/ is equivalent to 7/3and produces a result of 2.

%m Modulus (or remainder). For example, %{7}%{3}%m is equivalentto (7 mod 3) and produces a result of 1.

Modifying termcap and terminfo I-11

Page 780: Manual Informix

Adding Color and Intensity

Bit Operators

The following bit operators pop the top two values from the stack, performan operation, and push the result on the stack:

%& Bit-and. For example, %{12}%{21}%& is equivalent to (12 and 21)and produces a result of 4.

Binary Decimal

0 1 1 0 0 = 12

1 0 1 0 1 = 21

------------------------- and

0 0 1 0 0 = 4

%| Bit-or. For example, %{12}%{21}%| is equivalent to (12 or 21)and produces a result of 29.

Binary Decimal

0 1 1 0 0 = 12

1 0 1 0 1 = 21

------------------------- or

1 1 1 0 1 = 29

%^ Exclusive-or. For example, %{12}%{21}%^ is equivalent to (12exclusive-or 21) and produces a result of 25.

Binary Decimal

0 1 1 0 0 = 12

1 0 1 0 1 = 21

------------------------- exclusive or

1 1 0 0 1 = 25

The following unary operator pops the top value from the stack, performs anoperation, and pushes the result on the stack:

I-12 Modifying termcap and terminfo

Page 781: Manual Informix

Adding Color and Intensity

%~ Bitwise complement. For example, %{25}%~ results in a value of-26, as shown in the following display.

Binary Decimal

0 0 0 1 1 0 0 1 = 25

---------------------------- Complement

1 1 1 0 0 1 1 0 = -26

Logical Operators

The following logical operators pop the top two values from the stack, per-form an operation, and push the logical result (either 0 for false or 1 for true)on the stack:

%= Equal to. For example, if the parameter p1 has the value 3, theexpression %p1%{2}%= is equivalent to 3=2 and produces a resultof 0 (false).

%> Greater than. For example, if the parameter p1 has the value 3, theexpression %p1%{0}%> is equivalent to 3>0 and produces a resultof 1 (true).

%< Less than. For example, if the parameter p1 has the value 3, theexpression %p1%{4}%< is equivalent to 3<4 and produces a resultof 1 (true).

The following unary operator pops the top value from the stack, performs anoperation, and pushes the logical result (either 0 or 1) on the stack.

%! Logical negation. This operator produces a value of zero for allnonzero numbers and a value of 1 for zero. For example, %{2}%!results in a value of 0, and %{0}%! results in a value of 1.

Conditional Statements

The condition statement IF-THEN-ELSE has the following format:

%? expr %t thenpart %e elsepart %;

The %e elsepart is optional. You can nest conditional statements in the thenpartor the elsepart.

When INFORMIX-4GL evaluates a conditional statement, it pops the topvalue from the stack and evaluates it as either true or false . If the value istrue , INFORMIX-4GL performs the operations after the %t; otherwise it per-forms the operations after the %e (if any).

Modifying termcap and terminfo I-13

Page 782: Manual Informix

Adding Color and Intensity

For example, the expression

%?%p1%{3}%=%t;31%;

is equivalent to

if p1 = 3 then print ";31"

Assuming that p1 has the value 3, INFORMIX-4GL performs the followingsteps:

• %? does not perform an operation but is included to make the conditionalstatement easier to read.

• %p1 pushes the value of p1 on the stack.

• %{3} pushes the value 3 on the stack.

• %= pops the value of p1 and the value 3 from the stack, evaluates theBoolean expression p1=3, and pushes the resulting value 1 (true) onthe stack.

• %t pops the value from the stack, evaluates 1 as true , and executes theoperations after %t. (Since ‘‘;31’’ is not a stack machine operation, INFOR-MIX-4GL prints ‘‘;31’’ to the terminal.)

• %; terminates the conditional statement.

I-14 Modifying termcap and terminfo

Page 783: Manual Informix

Adding Color and Intensity

Summary of Operators

Figure I-8 summarizes the allowed operations:

Operation Description%d write pop() in decimal format%2d write pop() in 2-place decimal format%3d write pop() in 3-place decimal format%c write pop() as a single character

%p[1-9] push ith parameter%P[a-z] pop and store variable%g[a-z] get variable and push on stack%’c’ push char constant%{n} push integer constant%S[a-z] pop and store static variable%G[a-z] get static variable and push

%+ addition. push(pop() op pop())%- subtraction. push(pop() op pop())%* multiplication. push(pop() op pop())%/ integer division. push(pop() op pop())%m modulus. push(pop() op pop())

%& bit and. push(pop() op pop())%| bit or. push(pop() op pop())%^ bit exclusive or. push(pop() op pop())%~ bitwise complement. push(op pop())

%= equal to. push(pop() op pop())%> greater than. push(pop() op pop())%< less than. push(pop() op pop())%! logical negation. push(op pop())

%? expr %t thenpart %e elsepart %;if-then-else; the %e elsepart is optional.else-if’s are possible (c’s are conditions):%? c1 %t...%e c2 %t...%e c3 %t...%e...%;nested if’s allowed.

all other characters are written to the terminal;use ’%%’ to write ’%’.

Figure I-8 Stack Operations

Modifying termcap and terminfo I-15

Page 784: Manual Informix

Adding Color and Intensity

Examples

To illustrate, consider the monochrome Wyse terminal. Figure I-9 shows theescape sequences for various display characteristics.

ESC G 0 NormalESC G 1 blank(invisible)ESC G 2 blink

ESC G 4 ReverseESC G 5 Reverse and blankESC G 6 Reverse and blink

ESC G 8 UnderscoreESC G 9 Underscore and blankESC G : Underscore and blink

ESC G < Underscore and reverseESC G = Underscore, reverse, and blankESC G > Underscore, reverse, and blink

Figure I-9 Wyse Escape Sequences

The characters after G form an ASCII sequence from the character 0 (zero)through ?. You can generate the character by starting with 0 and adding 1 forblank, 2 for blink, 4 for reverse, and 8 for underline.

You can construct the termcap entry in stages, as outlined in the followingdisplay. %pi refers to pushing the ith parameter on the stack. The designationfor ESCAPE is \E . The termcap entry for the Wyse terminal must contain thefollowing ZA entry in order for INFORMIX-4GL monochrome attributes suchas REVERSE and BOLD to work correctly:

ZA =EG #print EG%’0’ #push ’0’ (normal) on the stack%?%p1%{7}%=%t%{1}%| #if p1 = 7 (invisible), set

#the 1 bit (blank);%e%p1%{3}%> #if p1 > 3 and < 7, set the 64 flag (dim);

%p1%{7}%<%&%t%{64}%| #%;%; #

%?%p2%t%{4}%|%; #if p2 is set, set the 4 bit (reverse)%?%p3%t%{2}%|%; #if p3 is set, set the 2 bit (blink)%?%p4%t%{8}%|%; #if p4 is set, set the 8 bit (underline)%c: #print whatever character

#is on top of the stack

I-16 Modifying termcap and terminfo

Page 785: Manual Informix

Adding Color and Intensity

You then concatenate these lines as a single string that ends with a colon andhas no embedded NEWLINEs. The actual ZA entry for the Wyse 50 terminalfollows:

ZA = \EG%’0’%?%p1%{7}%=%t%{1}%|%e%p1%{3}%>%p1%{7}%<%&%t%{64}%|%;%;%?%p2%t%{4}%|%;%?%p3%t%{2}%|%;%?%p4%t%{8}%|%;%c:

The next example is for the ID Systems Corporation ID231, a color terminal.On this terminal, to set color and other characteristics you must enclose acharacter sequence between a lead-in sequence (ESC [ 0 ) and a terminatingcharacter (m). The first in the sequence is a two-digit number that determineswhether the assigned color is in the background (30) or in the foreground(40). The next is another two-digit number that is the other of 30 or 40, incre-mented by the color number. These characters are followed by 5 if there isblinking, and by 4 for underlining.

The code in Figure I-10 sets up the entire escape sequence:

ZA =\E[0; #print lead-in%?%p1%{0}%=%t%{7} #encode color number (translate%e%p1%{1}%=%t%{3} # from Figure I-7 to the number%e%p1%{2}%=%t%{5} # for the ID231)%e%p1%{3}%=%t%{1} #%e%p1%{4}%=%t%{6} #%e%p1%{5}%=%t%{2} #%e%p1%{6}%=%t%{4} #%e%p1%{7}%=%t%{0}%; #%?%p2%t30;%{40}%+%2d #if p2 is set, print ’30’ and

# ’40’ + color number (reverse)%e40;%{30}%+%2d%; # else print ’40’ and

# ’30’ + color number (normal)%?%p3%t;5%; #if p3 is set, print 5 (blink)%?%p4%t;4%; #if p4 is set, print 4 (underline)m #print ’m’ to end character

# sequenceFigure I-10 Sample ZA String for ID231

When you concatenate these strings, the termcap entry is as shown inFigure I-11.

ZA =\E[0;%?%p1%{0}%=%t%{7}%e%p1%{1}%=%t%{3}%e%p1%{2}%=%t%{5}%e%p1%{3}%=%t%{1}%e%p1%{4}%=%t%{6}%e%p1%{5}%=%t%{2}%e%p1%{6}%=%t%{4}%e%p1%{7}%=%t%{0}%;%?%p2%t30;%{40}%+%2d%e40;%{30}%+%2d%;%?%p3%t;5%;%?%p4%t;4%;m

Figure I-11 Concatenated ZA String for ID231

Modifying termcap and terminfo I-17

Page 786: Manual Informix

The colornames File

In addition to the ZA capability, you can use other termcap capabilities. ZGis the number of character positions on the screen occupied by the attributesof ZA. Like the sg numeric capability, ZG is not required if no extra characterpositions are needed for display attributes. The value for the ZG entry is usu-ally the same value as for the sg entry.

The colornames FileYou can create a colornames file if you want to change the default assignmentof the names of colors. A colornames file is an ASCII file that changes the key-words that you use to write INFORMIX-4GL programs. It does not affect thecolors produced by your terminal. The format for the colornames file fol-lows:

name number. . . . . .

Explanation

name is the identifier of a color.

number is an integer from 0 to 7.

Notes

1. Each color name and number must be on a separate line. They should beseparated by one or more spaces or tabs.

2. name cannot be a reserved word and must be unique in the colornamesfile. You cannot assign the same name to more than one number.

3. Unless you redefine them in the colornames file to have a different num-ber, the default color-name keywords that are listed in the ‘‘Color andIntensity’’ section of this appendix (and in the next example) retain theirmeaning, even when you assign another name to that color number.

Examples

If you created a colornames file to set up the default assignment of names tocolor numbers, colornames would look as follows:

WHITE 0YELLOW 1MAGENTA 2RED 3CYAN 4

I-18 Modifying termcap and terminfo

Page 787: Manual Informix

The colornames File

GREEN 5BLUE 6BLACK 7

If you wanted to change CYAN to AQUA and MAGENTA to ORANGE as colornames, set colornames as follows:

AQUA 4ORANGE 2

You could use either CYAN or AQUA in your INFORMIX-4GL program andget the same color. Similarly, use of MAGENTA or ORANGE produces thesame color.

If you want to change the meaning of the default color names, you can reas-sign them in colornames:

RED 2

In this case when you use RED in a program, the color you get is the sameas has been assigned to MAGENTA. If you have not assigned a name to num-ber 3, you are not able to get the color that RED originally represented.

The syscolatt table and the ATTRIBUTE clauses of various 4GL statements canrecognize numeric color codes and non-default names for colors. You canspecify these names or numbers in place of the color keywords that are doc-umented in Chapter 7 and in the description of the upscol utility inAppendix E.

Note: You cannot, however, specify numeric codes or non-default names fromcolornames in the ATTRIBUTES section of a screen form.

Modifying termcap and terminfo I-19

Page 788: Manual Informix

terminfo

terminfoIf you have set the INFORMIXTERM environment variable to terminfo,INFORMIX-4GL uses the terminfo directory indicated by the TERMINFOenvironment variable (or /usr/lib/terminfo if TERMINFO is not set). INFOR-MIX-4GL uses the information in terminfo to draw window borders, definefunction keys, and display certain intensity attributes.

You may want to modify a file in the terminfo directory in the followinginstances:

• You want to extend function key definitions.

• You want to specify or change the graphics characters used for windowborders.

• You want to customize your terminal entry in other ways.

Note: If you use terminfo (instead of termcap), you cannot use color attributeswith INFORMIX-4GL. To use color attributes with INFORMIX-4GL, you must usetermcap.

Some terminals cannot support graphics characters. You should read thisappendix and the user guide that comes with your terminal to determinewhether or not the changes described in this appendix are applicable to yourterminal.

To modify a terminfo file, you need to be familiar with the following:

• The format of terminfo entries

• The infocmp program

• The tic program

This information is summarized in this appendix; however, you should referto your operating system documentation for a complete discussion.

Format of a terminfo Entryterminfo is a directory that contains a file for each terminal name that isdefined. Each file contains a compiled terminfo entry for that terminal. Thissection describes the general format of terminfo entries. For a completedescription of terminfo, refer to your operating system documentation.

I-20 Modifying termcap and terminfo

Page 789: Manual Informix

Format of a terminfo Entry

A terminfo entry contains a list of names for the terminal, followed by a listof the terminal’s capabilities. There are three types of capabilities:

• Boolean capabilities

• Numeric capabilities

• String capabilities

All terminfo entries have the following format:

• ESCAPE is specified as a backslash ( \ ) followed by the letter E, and CTRLis specified as a caret (^). Do not use the ESCAPE or CTRL keys to indicateescape sequences or control characters in a terminfo entry.

• Each capability, including the last one in the entry, is followed by acomma ( , ).

Figure I-12 shows a basic terminfo entry for the Wyse 50 terminal:

. Entry for Wyse 50:

w5|wy50|wyse50,am, cols#80, lines#24, cuul=^K, clear=^Z,home=^^, cuf1=^L, cup=\E=%p1%’\s’%+%c%p2%’\s’%+%c,bw, ul, bel=^G, cr=\r, cud1=\n, cub1=\b, kpb=\b, kcudl=\n,kdub1=\b, nel=\r\n, ind=\n,xmc#1, cbt=\EI,

Figure I-12 Wyse 50 terminfo Entry

Note: Comment lines begin with a period ( . ).

Terminal Names

A terminfo entry starts with one or more names for the terminal (each sepa-rated by a vertical bar ( | )). For example, the terminfo entry for the Wyse 50terminal starts with the following line:

w5|wy50|wyse50,

The terminfo entry can be accessed using any one of these names.

Boolean Capabilities

A Boolean capability is a two- to five-character code that indicates whetheror not a terminal has a specific feature. If the Boolean capability is present inthe terminfo entry, the terminal has that particular feature.

Modifying termcap and terminfo I-21

Page 790: Manual Informix

Format of a terminfo Entry

Figure I-13 shows some of the Boolean capabilities for the Wyse 50:

bw,am,

. bw backward wrap

. am automatic marginsFigure I-13 Boolean Capabilities for the Wyse 50

Numeric Capabilities

A numeric capability is a two- to five-character code followed by a poundsymbol ( # ) and a value. Figure I-14 shows the numeric capabilities for thenumber of columns and the number of lines on a Wyse 50 terminal:

cols#80,lines#24,

. cols number of columns in a line

. lines number of lines on the screenFigure I-14 Numeric Capabilities for the Wyse 50

String Capabilities

A string capability specifies a sequence that can be used to perform a terminaloperation. A string capability is a two- to five-character code followed by anequal sign ( = ) and a string ending at the next delimiter ( , ).

Most terminfo entries include string capabilities for clearing the screen, cur-sor movement, arrow keys, underscore, function keys, and so on. Figure I-15shows many of the string capabilities for the Wyse 50 terminal:

el=\ET,clear=E*,cuf1=^L,cuu1=^K,smso=\EG4,rmso=\EG0,kcuu1=^K,kcud1=^J,kcuf1=^L,kcub1=^H,kf0=^A@^M,kf1=^AA^M,kf2=^AB^M,kf3=^AC^M,

. el=\Et clear to end of line

. clear=\E* clear the screen

. cufl=^L non-destructive cursor right

. cuul=^K up one line

.

. smso=\EG4 start stand-out

. rmso=\EG0 end stand-out

.

I-22 Modifying termcap and terminfo

Page 791: Manual Informix

Extending Function Key Definitions

. kcuul=^K up arrow key

. kcudl=^J down arrow key

. kcufl=^L right arrow key

. kcubl=^H left arrow key

.

. kf0=^A@^M function key F1

. kf1=^AA^M function key F2

. kf2=^AB^M function key F3

. kf3=^AC^M function key F4Figure I-15 String Capabilities for the Wyse 50

Extending Function Key DefinitionsINFORMIX-4GL recognizes function keys F1 through F36. These keys corre-spond to the terminfo capabilities kf0 through kf36. The terminfo entry forthese capabilities is the sequence of ASCII characters that your terminalsends when you press the function keys (or any other keys you choose to useas function keys). For the Wyse 50 and Televideo 950 terminals, the first eightfunction keys send the characters shown in Figure I-16.

Function Key terminfo EntryF1 kf0=^A@^MF2 kf1=^AA^MF3 kf2=^AB^MF4 kf3=^AC^MF5 kf4=^AD^MF6 kf5=^AE^MF7 kf6=^AF^MF8 kf7=^AG^M

Figure I-16 Function Key Entries for the Wyse 50

You can also define keys that correspond to the following capabilities:

• Insert line (kill)

• Delete line (kdll)

• Next page (knp)

• Previous page (kpp)

If these keys are defined in your terminfo file, INFORMIX-4GL uses them.Otherwise, INFORMIX-4GL uses CTRL-J, CTRL-K, CTRL-M, and CTRL-N,respectively.

Note: You can also use the OPTIONS statement to name other function keys orCTRL keys for these operations.

Modifying termcap and terminfo I-23

Page 792: Manual Informix

Specifying Characters for Window Borders

Specifying Characters for Window BordersINFORMIX-4GL uses characters defined in the terminfo files to draw the bor-der of a window. If no characters are defined in this file, INFORMIX-4GL usesthe hyphen ( - ) for horizontal lines, the vertical bar ( | ) for vertical lines, andthe plus sign ( + ) for corners.

You can look at the terminfo source file (using infocmp) to see if the entry foryour terminal includes these definitions. (Look for the acsc capability,described later in this section.) If the file for your terminal does not containborder character definitions, or if you want to specify alternative border char-acters, you or your system administrator can modify the terminfo source file.You can refer to your operating system documentation for a completedescription of how to decompile terminfo entries using the infocmpprogram.

Perform the following steps to specify border characters in the terminfosource file for your terminal:

1. Determine the escape sequences for turning graphics mode on and off.This information is located in the manual that comes with your terminal.For example, on Wyse 50 terminals, the escape sequence for enteringgraphics mode is ESC H^B and the escape sequence for leaving graphicsmode is ESC H^C.

Note: Terminals without a graphics mode do not have this escape sequence. Theprocedure for specifying alternative border characters on a non-graphics terminalis discussed at the end of this section.

2. Identify the ASCII equivalents for the six graphics characters that INFOR-MIX-4GL requires to draw the border. (The ASCII equivalent of a graphicscharacter is the key you would press in graphics mode to obtain the indi-cated character.)

Figure I-17 shows the graphics characters and the ASCII equivalents for aWyse 50 terminal.

I-24 Modifying termcap and terminfo

Page 793: Manual Informix

Specifying Characters for Window Borders

Windown Border Graphics ASCIIPosition Character Equivalent

upper left corner 2lower left corner 1upper right corner 3lower right corner 5horizontal - zvertical | 6

Figure I-17 Wyse 50 ASCII Equivalents for Border Graphics Characters

Again, this information should be located in the manual that comes withyour terminal.

3. Edit the terminfo source file for your terminal. (You can decompile itusing infocmp redirected to a file.)

Note: You may want to make a copy of your terminfo directory before you editfiles. You can use the TERMINFO environment variable to point to whichevercopy of the terminfo directory you want to access.

Use the format

terminfo-capability=valueto enter values for the following terminfo capabilities:

smacs The escape sequence for entering graphics mode. In a terminfofile, ESCAPE is represented as a backslash ( \ ) followed by the let-ter E; CTRL is represented as a caret ( ^ ). For example, the Wyse50 escape sequence ESC-H CTRL-B is represented as \EH^B.

rmacs The escape sequence for leaving graphics mode. For example, theWyse 50 escape sequence ESC-H CTRL-C is represented as \EH^C.

acsc The concatenated, paired list of ASCII equivalents for the sixgraphics characters used to draw the border. You can specify thecharacters in any order, but you must pair the ASCII equivalentsfor your terminal with the following system default characters:

Modifying termcap and terminfo I-25

Page 794: Manual Informix

Specifying Characters for Window Borders

System DefaultPosition Characterupper left corner llower left corner mupper right corner klower right corner jhorizontal lines qvertical lines x

Figure I-18 System Default Characters for Border Positions

Use the following format to specify the acsc value:

defnewdefnew . . .

where def is the default character for a particular border character and newis that terminal’s equivalent for the same border character.

For example, on the Wyse 50 terminal, given the ASCII equivalents inFigure I-17 and the system default characters in Figure I-18, the acsc capa-bility would be set as shown in Figure I-19.

acsc=l2m1k3j5qzx6Figure I-19 Wyse 50 acsc setting

4. Use tic to recompile the modified terminfo file. See your operating sys-tem documentation for a description of the tic program.

The following example shows the full setting for specifying alternativeborder characters on the Wyse 50:

smacs=\EH^B, . sets smacs to ESC H CTRL Brmacs=\EH^C, . sets rmacs to ESC H CTRL Cacsc=l2m1k3j5qzx6, . sets acsc to the ASCII equivalents

. of graphics characters for upper

. left (l), lower left (m), upper right (k),

. lower right (j), horizontal (q),

. and vertical (x)

If you prefer, you can enter this information in a linear sequence.

smacs=\EH^B,rmacs=\EH^C,acsc=l2m1k3j5qzx6,

Terminals Without Graphics Capabilities

For terminals without graphics capabilities, you must enter a blank value forthe smacs and rmacs capabilities. For acsc, enter the characters that you wantINFORMIX-4GL to use for the window border.

I-26 Modifying termcap and terminfo

Page 795: Manual Informix

Color and Intensity

The following example shows possible values for smacs, rmacs, and acsc inan entry for a terminal without graphics capabilities. In this example, win-dow borders would be drawn using underscores ( _ ) for horizontal lines, ver-tical bars ( | ) for vertical lines, periods ( . ) for the top corners, and verticalbars ( | ) for the lower corners.

smacs=,rmacs=,acsc=l.m|k.j|q_x|,

INFORMIX-4GL uses the graphics characters in the terminfo file when youspecify a window border in an OPEN WINDOW statement.

Color and IntensityIf you use terminfo, you cannot use color nor the following intensityattributes in your INFORMIX-4GL programs:

BOLDDIMINVISIBLEBLINK

If you specify these attributes in your INFORMIX-4GL code, they are ignored.

If the terminfo entry for your terminal contains the ul and so attributes, youcan use the UNDERLINE and REVERSE intensity attributes. You can see if yourterminfo entry includes these capabilities by using the infocmp program.Refer to your operating system documentation for information about info-cmp.

If you want to use color and intensity in your INFORMIX-4GL programs, youmust use termcap (by setting the INFORMIXTERM environment variable totermcap, and by setting the TERMCAP environment variable to $INFOR-MIXDIR/etc/termcap). For more information, refer to the ‘‘EnvironmentVariables’’ appendix and the Preface in the INFORMIX-4GL User Guide.

Modifying termcap and terminfo I-27

Page 796: Manual Informix

Color and Intensity

I-28 Modifying termcap and terminfo

Page 797: Manual Informix

Appendix

J

Working withDATETIME andINTERVAL DataThe DATETIME and INTERVAL data types provide a way ofstoring moments in time and the spans between moments.The DATETIME data type holds a value that represents asingle point in time. You choose how precisely a DATETIMEvalue is stored; its precision can range from years throughfractions of a second. The INTERVAL data type holds avalue that represents a span of time. It can represent eithera span of years and months, or else a span of days, hours,minutes, seconds, and fractions of a second.

You can specify DATETIME and INTERVAL values in a formthat explicitly identifies not only the value but also the datatype (DATETIME or INTERVAL) and the precision, or youcan enter values as quoted character strings that includeonly the values. The explicit form, sometimes called a lit-eral, appears throughout this appendix (except as noted),but character strings (which omit the data type and fieldnames) may be required in interactive operations, such asquery by example or data entry through screen forms.

You can manipulate DATETIME and INTERVAL values in anumber of ways. You can enter them as data, you can usethem in relational expressions, and you can manipulatethem arithmetically. This appendix supplies you withguidelines on how you can use DATETIME and INTERVALvalues. Note, however, that many of the examples pre-sented here are fragmentary. That is, they do not include the

Page 798: Manual Informix

DATETIME Columns

full syntax necessary for an executable statement. (The section“Data Manip-ulation Statements” presents examples of complete SQL statements that useDATETIME and INTERVAL values.)

DATETIME ColumnsUse the DATETIME data type for columns or variables in which you want tostore values that represent a specific point in time. The DATETIME data typeis composed of a contiguous sequence of fields that represent each compo-nent of time that you want to record. This is the syntax for defining aDATETIME column or program variable:

identifier DATETIME first TO last

Here first and last are fields taken from the following list:

Field Valid Entries

YEAR A year, numbered from 1 to 9999.

MONTH A month, numbered from 1 to 12.

DAY A day, numbered from 1 to 31, as appropriate to the month in question.

HOUR An hour, numbered from 0 (midnight) to 23.

MINUTE A minute, numbered from 0 to 59.

SECOND A second, numbered from 0 to 59.

FRACTION A fraction of a second with up to five decimal digits. The default scaleis three digits (thousandth of a second). You can explicitly change thisby writing FRACTION (n), where n is the desired number of digitsfrom 1 to 5.

A DATETIME column or variable need not include all fields from YEAR toFRACTION. It can be a subset of fields, or even a single field (if first and lastare identical). You can define a DATETIME column or variable to include onlythe fields that you need. For example, you can specify MONTH TO HOUR toinclude only MONTH, DAY, and HOUR. Since the fields are contiguous, theyinclude all fields from first to last in the sequence listed above. But you cannotspecify HOUR TO YEAR, because first cannot be a smaller unit than last.

Operations involving DATETIME values that do not include precision up toYEAR use the system date to supply any additional precision required. Whenthe first field is DAY and the current month has less than 31 days, you can

J-2 Working with DATETIME and INTERVAL Data

Page 799: Manual Informix

Specifying DATETIME Values

encounter unexpected results. For example, assume it is February, and youwant to insert data left over from January 31 into the table created by the fol-lowing statement:

CREATE TABLE mytable (mytime DATETIME DAY TO MINUTE)INSERT INTO mytable VALUES (DATETIME(31 12:30) DAY TO MINUTE)

Because the column mytime does not include the month or year, the currentmonth and year are used to evaluate whether the inserted value is withinacceptable bounds. February has only 28 (or 29) days, so no value for DAYcan be larger than 28 (or 29). The INSERT statement in this example wouldfail, because the value 31 for DAY is out of range for February. If your appli-cation requires that DATETIME inserts span months in this way, always defineDATETIME columns with precision up to at least MONTH.

Specifying DATETIME ValuesThere is a rigid syntax that you must observe when you insert DATETIMEconstants into DATETIME columns or variables. If you use the literal form,you must supply the actual date and time values, with proper delimitersbetween the fields, and a list of the first and last fields that you are specifying.(A later section of this appendix describes character string formats.)

Just as you can define a DATETIME column or variable to be only a subset ofall possible fields, you can also specify values that contain just a subset of thedeclared fields of a DATETIME column or variable. For example, you canenter a value consisting of just MONTH, DAY, and HOUR into a column thatis defined as YEAR TO MINUTE. Each value, however, must always containinformation for a contiguous sequence of fields. For example, you cannotspecify a value for just MONTH and HOUR. The entry must include a valuefor DAY as well.

When you specify a value with fewer fields than the defined column or vari-able, the value that you enter is automatically expanded to fill all the definedfields. If you omit a more significant field (that is, a field of a larger unit thanany value that you supply), that field is automatically filled with the systemdate. In the previous example, YEAR is omitted, so the current year is auto-matically inserted into your entry. Alternatively, if you omit a less significantfield, that field is filled with zeros (or one for MONTH and DAY ) in your entry.In the previous example, MINUTE is left out, so zeros are inserted into theMINUTE field for your entry.

Consider the following example:

CREATE TABLE mytable (mytime DATETIME YEAR TO MINUTE)INSERT INTO mytable VALUES (DATETIME (8-31 12) MONTH TO HOUR)

Working with DATETIME and INTERVAL Data J-3

Page 800: Manual Informix

Specifying DATETIME Values

Even though the column mytime has a defined precision of YEAR to MINUTE,you can supply information for only MONTH to HOUR. The entered value isautomatically expanded to fill the column. If the current year is 1989, theactual inserted value becomes:

DATETIME (1989-8-16 12:00) YEAR TO MINUTE

Notice that the current year, in this example 1989, has been added automati-cally, along with zeros for the MINUTE field.

The current date is also used to evaluate whether a DATETIME value thatdoes not include precision up to YEAR is an acceptable date. This can causeproblems when the largest precision of the value is DAY. For example,assume the current month is September, and you attempt to execute the fol-lowing statements:

CREATE TABLE mytable (mytime DATETIME DAY TO MINUTE)INSERT INTO mytable VALUES (DATETIME (31 12) DAY TO HOUR)

Before the row is inserted, the validity of the DATETIME value is checkedagainst the current date. Because September has only 30 days, the 31 for DAYis out of range and will produce an error. As a result, you cannot insert thisrow during a month that has fewer than 31 days.

Caution: In order to eliminate the risk of processing difficulties during monthswith fewer than 31 days, do not create DATETIME columns or variables with a firstprecision of DAY, and do not enter DATETIME values with DAY as the field oflargest precision.

When you enter a DATETIME literal, you must include a qualifier that specifiesboth the first (largest) and last (smallest) field in the value to be entered.Including the qualifier is necessary because, as noted earlier, the value thatyou are entering can contain fewer fields than defined for that column orvariable. Acceptable keywords for the first and last fields are identical to thelist of valid DATETIME fields displayed previously.

A valid entry contains the DATETIME name, the values to be entered, and thefield qualifier. Use the syntax first-field TO last-field to qualify the DATETIMEvalue. For example, in the following entry, YEAR TO FRACTION indicates thatvalues for all possible fields are included in the values listed between theparentheses. The order of entry and the type of delimiter identify whichvalue corresponds to each field.

DATETIME (1985-5-2 14:05:00.000) YEAR TO FRACTION

J-4 Working with DATETIME and INTERVAL Data

Page 801: Manual Informix

INTERVAL Columns

The following examples illustrate values that do not include all fields:

DATETIME (89-8-16) YEAR TO DAYDATETIME (16 12:23) DAY TO MINUTEDATETIME (21.234) SECOND TO FRACTIONDATETIME (32) SECOND TO SECONDDATETIME (.0032) FRACTION TO FRACTION(4)

When YEAR is given as a two-digit number, as in the first example, it is auto-matically changed to ‘‘19xx’’ (‘‘1989’’ in this case). If you want to specify years1-99, pad the entry with a preceding zero(s), for example ‘‘089’’ or ‘‘0089.’’When a value occupies only one field, the first and last qualifiers are thesame. If the first and last qualifiers are both FRACTION, you specify the preci-sion only for the last field.

Values for the fields are written as integers and are separated by delimiters.All field values are two-digit integers, except for the YEAR (four digits) andFRACTION (n digits) fields. The following delimiters are used withDATETIME values:

Delimiter Placement in DATETIME Expression

hyphen ( - ) Between the YEAR and MONTH, and between the MONTH andDAY portions of the value.

space ( ) Between the DAY and HOUR portions of the value.

colon ( : ) Between the HOUR and MINUTE, and MINUTE and SECONDportions of the value.

period ( . ) Between the SECOND and FRACTION portions of the value.

You use the same delimiters when DATETIME values are expressed as char-acter strings.

INTERVAL ColumnsLike the DATETIME data type, the INTERVAL data type is composed of a con-tiguous sequence of fields. Here is the syntax for defining an INTERVALcolumn:

identifier INTERVAL first TO last

Here first and last are fields taken from one of the following two lists:

Field Valid Entries

YEAR A number of years.

MONTH A number of months.

OR

Working with DATETIME and INTERVAL Data J-5

Page 802: Manual Informix

Specifying INTERVAL Values

DAY A number of days.

HOUR A number of hours.

MINUTE A number of minutes.

SECOND A number of seconds.

FRACTION A fraction of a second, with up to five decimal digits. The defaultscale is three digits (thousandth of a second). You can change thisby explicitly writing FRACTION(n), where n is the desired numberof digits from 1 to 5.

As with a DATETIME column, you can define an INTERVAL column to includeonly the fields that you need. An INTERVAL value can contain either YEARand MONTH information or DAY through FRACTION information, but not acombination of both. The reason for this is that the INTERVAL data type isdesigned specifically to represent a span of time independent of actual dates.The number of days in a month depends on which month it is. INTERVALdata cannot be month-dependent; therefore, it is not possible to combinemonths and days in an INTERVAL value.

Specifying INTERVAL ValuesLike its DATETIME counterpart, a value that you enter into an INTERVAL col-umn need not include all the declared fields. For example, you can enter avalue consisting of HOUR, MINUTE, and SECOND fields into a columndefined as DAY TO SECOND. A value must always consist, however, of a con-tiguous sequence of fields. For example, you cannot specify just HOUR andSECOND values; you must include MINUTE as well.

When you enter a value in an INTERVAL column, you must include a qualifierthat specifies both the first (largest) and last (smallest) fields in the value, justas for DATETIME values. In addition, you can specify the precision of the firstfield (and of the the last field if it is FRACTION). Acceptable qualifiers for thefirst field and last field are identical to the list of INTERVAL fields previouslydisplayed, with the same restriction that YEAR and MONTH cannot be com-bined with the smaller fields.

You write INTERVAL values in the same literal format as DATETIME values.A valid entry contains the INTERVAL name, the values to be entered, and thefield qualifier. For example, the following entries are valid INTERVAL values:

INTERVAL (5-3) YEAR TO MONTHINTERVAL (9) MONTH TO MONTHINTERVAL (12:23) HOUR TO MINUTE

J-6 Working with DATETIME and INTERVAL Data

Page 803: Manual Informix

Specifying INTERVAL Values

Each entry represents a span of time: 5 years and 3 months; 9 months; and 12hours and 23 minutes, respectively. None of the entries refer to a specificpoint in time. For example, the nine-month interval could represent a spanfrom any single year or across any two years.

When a value contains just one field, the first and last qualifiers are the same.If the first and last qualifiers are both FRACTION, you can only specify theprecision in the last field.

The first field in an INTERVAL value can be up to nine digits in size (exceptfor FRACTION, which cannot be more than five digits), but if the value isgreater than the default number of digits allowed for that field, you mustexplicitly identify the number of significant digits in the value you are enter-ing. By default, you are allowed up to four digits in a year, three digits in afraction, and two digits in all other fields. If you need more digits than thedefault, enter the number of required digits (between parentheses) after thefield qualifier.

INTERVAL (10000-2) YEAR(5) TO MONTHINTERVAL (127) MONTH(3) TO MONTHINTERVAL (365 0:23) DAY(3) TO MINUTEINTERVAL (1421 36:25:54.93721) DAY(4) TO FRACTION(5)

The first example illustrates how you can specify a span of 10,000 years byincluding the number five (5) after the YEAR. The second example allows athree-digit MONTH entry. Notice that the number is attached to the first qual-ifier. You will get a syntax error if you attach the number to the last qualifier.The third example is a DAY TO MINUTE span of 1 year and 23 minutes. Thisillustrates how you can represent values of any length by converting yearsand months into their corresponding number of days. Note also how you caninclude a zero for the HOUR field in order to enter a value just for MINUTE.The last example shows how you can specify the precision of both first andlast when FRACTION is the last field.

Non-default precisions are a feature of INTERVAL data. An error results ifyou use this notation to specify any DATETIME field except FRACTION.

INTERVAL data follow normal date and time conventions concerning therange of acceptable values that you can enter. An error results if you exceedthe possible values for a given field. Note the following examples:

INTERVAL (5-13) YEAR TO MONTHINTERVAL (6-1) YEAR TO MONTH

The first example causes an error because 13 months is more than a year. Thesecond example correctly expresses the same span of time.

Working with DATETIME and INTERVAL Data J-7

Page 804: Manual Informix

DATETIME and INTERVAL Values as Character Strings

The values for the fields are written as integers and are separated by delimit-ers. The following delimiters are used with INTERVAL values:

Delimiter Placement in INTERVAL Expression

hyphen ( - ) Between the YEAR and MONTH portions of the value.

space ( ) Between the DAY and HOUR portions of the value.

colon ( : ) Between the HOUR and MINUTE, and MINUTE and SECONDportions of the value.

period ( . ) Between the SECOND and FRACTION portions of the value.

DATETIME and INTERVAL Values as Character StringsYou can enter DATETIME and INTERVAL data in the literal forms described inthe previous sections or as quoted character strings. The following examplesillustrate both formats:

CREATE TABLE mytable(mytime DATETIME YEAR TO DAY, myval INTERVAL DAY TO SECOND)

INSERT INTO mytable(mytime) VALUES (DATETIME(89-5-12) YEAR TO DAY)INSERT INTO mytable(mytime) VALUES ("89-5-12")

INSERT INTO mytable(myval) VALUES (INTERVAL(17 11:15:30) DAY TO SECOND)INSERT INTO mytable(myval) VALUES ("17 11:15:30")

Values that are specified as character strings are automatically converted intoDATETIME or INTERVAL values. You can use character strings whenever youspecify information for all fields defined for that DATETIME or INTERVALcolumn.

When a character string is converted into a DATETIME or INTERVAL value,the engine assumes that the character string includes information about allthe defined fields. You cannot use character strings to enter DATETIME orINTERVAL values for a subset of fields, because this produces ambiguous val-ues. If the character string does not contain information for all fields, theengine returns an error. For example:

INSERT INTO mytable(mytime) VALUES (DATETIME(5-12) MONTH TO DAY)INSERT INTO mytable(mytime) VALUES ("5-12")

INSERT INTO mytable(myval) VALUES (INTERVAL(11:15) HOUR TO MINUTE)INSERT INTO mytable(myval) VALUES ("11:15")

The previous DATETIME example (column mytime) enters a MONTH andDAY value into a column defined as YEAR TO DAY. Entering only these valuesis appropriate in the first INSERT statement, because there you tell the enginethat there is no YEAR information. In this case, the engine automatically adds

J-8 Working with DATETIME and INTERVAL Data

Page 805: Manual Informix

Operations on DATETIME and INTERVAL Values

the current year. The character string, however, does not indicate what infor-mation is omitted. The engine does not know whether the ‘‘5-12’’ refers toYEAR and MONTH, or MONTH and DAY, so it returns an error.

The previous INTERVAL example (column myval) enters an HOUR andMINUTE value into a column defined as DAY TO SECOND. The first INSERTstatement simply pads the value with zeros for YEAR and SECOND. The sec-ond INSERT statement produces a conversion error, because the engine doesnot know whether the ‘‘11:15’’ refers to HOUR TO MINUTE or MINUTE TOSECOND.

Operations on DATETIME and INTERVAL ValuesYou can use DATETIME and INTERVAL data in a variety of arithmetic andBoolean expressions. You can manipulate a DATETIME value in conjunctionwith another DATETIME, a DATE, or an INTERVAL value, the current date andtime (from the keyword CURRENT), the current date (TODAY), or some quan-tity of a specified unit of time (identified by the keyword UNITS). You cansimilarly manipulate an INTERVAL value. In addition, you can multiply ordivide an INTERVAL value by a number.

An INTERVAL column can hold a value that represents the differencebetween two DATETIME values, or the difference (or sum) of two INTERVALvalues. In either case, the result is a span of time, which is an INTERVALvalue. On the other hand, if you add or subtract an INTERVAL value from aDATETIME or DATE value, you get a DATETIME value, because the result is aspecific point in time.

The following table indicates the range of arithmetic expressions that you canuse with DATETIME (or DATE) and INTERVAL data, along with the data typeresulting from each expression.

Data Type of Data Type ofOperand 1 Operator Operand 2 ResultDatetime - Datetime IntervalDatetime + or - Interval DatetimeInterval + Datetime DatetimeInterval + or - Interval IntervalDatetime - CURRENT IntervalCURRENT - Datetime IntervalInterval + CURRENT DatetimeCURRENT + or - Interval DatetimeDatetime + or - UNITS DatetimeInterval + or - UNITS IntervalInterval * or / Number Interval

Working with DATETIME and INTERVAL Data J-9

Page 806: Manual Informix

Manipulating DATETIME Values

You can substitute a DATE value for a DATETIME operand in this table toobtain a DATETIME or INTERVAL result, except that the difference betweentwo DATE values is an INTEGER number of days. See the last section of thisappendix for more information on using DATE values in expressions withDATETIME or INTERVAL values.

No other combinations are allowed. You cannot add DATETIME or DATE val-ues, because this operation does not produce either a point in time or a spanof time. For example, you cannot add December 25 to January 1, though youcan subtract it to find the span between the two dates. Examples of validDATETIME expressions are presented in the following sections.

Manipulating DATETIME ValuesYou can subtract most DATETIME values from each other. The result is eithera positive or negative INTERVAL. The first DATETIME value determines thefield precision for the result. If the second DATETIME value has fewer fieldsthan the first, the shorter value is automatically extended to match the longerone. If the second DATETIME value has more fields than the first (regardlessof whether the precision of the extra fields is larger or smaller than those inthe first value), the additional fields in the second value are ignored in thecalculation.

DATETIME (1989-9-30 12:30) YEAR TO MINUTE- DATETIME (1989-8-1 11) YEAR TO HOURresult: INTERVAL (60 01:30) DAY TO MINUTE

DATETIME (1989-9-30) YEAR TO DAY- DATETIME (10-1) MONTH TO DAYresult: INTERVAL (-1) DAY TO DAY [assuming current year is 1989]

In the first example, no MINUTE field is included for the second value, so theminutes are automatically set to zero, and the resulting INTERVAL is 60 days,1 hour, and 30 minutes. In the second example, the year is not included forthe second value. Therefore, the year is automatically set to the current year,in this case 1989, and the resulting INTERVAL is negative, to show that thesecond date is later than the first.

J-10 Working with DATETIME and INTERVAL Data

Page 807: Manual Informix

Manipulating DATETIME with INTERVAL Values

Manipulating DATETIME with INTERVAL ValuesINTERVAL values can be added to or subtracted from DATETIME or DATEvalues. The result is a DATETIME value. If you are adding an INTERVAL to aDATETIME or DATE, the order of values is unimportant. If you are subtract-ing, however, the DATETIME or DATE value must come first.

DATETIME (1989-8-1) YEAR TO DAY+ INTERVAL (3-5) YEAR TO MONTHresult: DATETIME (1993-01-01) YEAR TO DAY

DATETIME (15:45) HOUR TO MINUTE- INTERVAL (720) MINUTE(3) TO MINUTEresult: DATETIME (3:45) HOUR TO MINUTE

Adding or subtracting a non-zero INTERVAL value returns a DATETIMEvalue that is earlier or later in time than the DATETIME or DATE operand inthe expression. The first example that follows moves the date ahead by threeyears and five months. The second example moves the value back by 12hours. This result, however, is presented as 720 minutes, a three-digit num-ber. Since this precision exceeds the default of two digits, you must explicitlydefine the first qualifier as MINUTE(3).

In most situations, the database engine automatically adjusts the calculationwhen the initial values do not have the same precision. However, there arecertain situations where you must explicitly adjust the precision of one valuein order to perform the calculation.

If the INTERVAL value that you are adding or subtracting includes any fieldthat is not included in the DATETIME or DATE value, you must explicitly usethe EXTEND function to return an adjusted DATETIME value for the arith-metic operation. (For more information, see the description of EXTEND( )near the end of Chapter 2.) For example, you cannot directly subtract the 720minute INTERVAL in the second example from the DATETIME value in thefirst example that has a precision from YEAR to DAY. You can perform this cal-culating by using the EXTEND function:

EXTEND (DATETIME (1989-8-1) YEAR TO DAY, YEAR TO MINUTE)- INTERVAL (720) MINUTE(3) TO MINUTEresult: DATETIME (1989-07-31 12:00) YEAR TO MINUTE

The EXTEND function returns a DATETIME value whose precision isexpanded from YEAR TO DAY to YEAR TO MINUTE. This allows the databaseengine to perform the calculation, and the result has the extended precisionof YEAR to MINUTE from the first operand.

Working with DATETIME and INTERVAL Data J-11

Page 808: Manual Informix

Manipulating INTERVAL Values

The following examples use DATE values in expressions that evaluate toDATETIME values.

DEFINE calendar DATELET calendar = "05/18/1990"

calendar - INTERVAL (5-5) YEAR TO MONTHresult: DATETIME (1984-12-18) YEAR TO DAY

EXTEND(calendar, YEAR TO HOUR) - INTERVAL (4 8) DAY TO HOURresult: DATETIME (1990-05-13 16) YEAR TO HOUR

You cannot directly combine a DATE with an INTERVAL value whose lastqualifier is smaller than DAY. But as the previous example shows, you can usethe EXTEND function to convert the value in a DATE column or variable to aDATETIME value that includes all the fields of the INTERVAL operand.

Manipulating INTERVAL ValuesINTERVAL values can be added and subtracted from each other only if bothvalues are of similar precision. That is, both must be qualified in the rangeYEAR to MONTH, or else both must be in the range DAY to FRACTION. Withinthese ranges, the qualifiers need not be identical.

INTERVAL (5-3) YEAR TO MONTH+ INTERVAL (15) MONTH TO MONTHresult: INTERVAL (6-06) YEAR TO MONTH

INTERVAL (100:30.0005) MINUTE(3) TO FRACTION(4)- INTERVAL (120.01) SECOND(3) TO FRACTIONresult: INTERVAL (98:29.9905) MINUTE TO FRACTION(4)

In the first example, a MONTH value is added to a YEAR TO MONTH value.The result (15 months) is automatically converted into years and months,resulting in a total INTERVAL value of 6 years and 6 months. In the secondexample, a SECOND TO FRACTION value is subtracted from a MINUTE TOFRACTION value. Note the use of numeric qualifiers (in parentheses) to alertthe engine that the MINUTE and FRACTION in the first value and the SECONDin the second value exceed the default number of digits.

J-12 Working with DATETIME and INTERVAL Data

Page 809: Manual Informix

Operations Using CURRENT Values

Operations Using CURRENT ValuesCURRENT is a keyword that evaluates to the current date and time. You canuse it in place of a specific DATETIME value. The following examples ofexpressions with CURRENT assume that CURRENT is executed when the sys-tem clock returns a value equivalent to DATETIME (1989-8-1 00:00:00.000)YEAR TO FRACTION:

DATETIME (1989-9-30 12:30) YEAR TO MINUTE - CURRENTresult: INTERVAL (60 12:30) DAY TO MINUTE

CURRENT - DATETIME (10-1) MONTH TO DAYresult: INTERVAL (-61 00:00:00.000) DAY TO FRACTION

CURRENT + INTERVAL (3-5) YEAR TO MONTHresult: DATETIME (1993-01-01 00:00:00.000) YEAR TO FRACTION

CURRENT - INTERVAL (720) MINUTE(3) TO MINUTEresult: DATETIME (1989-07-31 12:00:00.000) YEAR TO FRACTION

The precision of the first value determines the precision of output whenusing DATETIME values. In the first example, the precision used for CUR-RENT matches the first DATETIME value, YEAR TO MINUTE, so the resultingINTERVAL value has precision DAY TO MINUTE. The precision of the otherthree examples is determined by CURRENT, which uses the default precisionof YEAR TO FRACTION.

Similarly, you can specify the TODAY keyword in arithmetic expressionswhere a DATE value can appear.

Operations Using UNITS ValuesA shorthand way to represent single-field INTERVAL values is to use theUNITS keyword. It allows you to specify quickly amounts of a field (for exam-ple, number of years) that you want to add to or subtract from a DATETIMEor INTERVAL value. UNITS has the following syntax:

number UNITS field-name

Working with DATETIME and INTERVAL Data J-13

Page 810: Manual Informix

Multiplying or Dividing INTERVAL Values

where number is the amount and field-name is the type of field. The followingexamples repeat previous examples, except UNITS replaces one of theINTERVAL values.

DATETIME (1989-8-1) YEAR TO DA Y + 3 UNITS YEARresult: DATETIME (1992-08-01) YEAR TO DAY

DATETIME (15:45) HOUR TO MINUTE - 720 UNITS MINUTEresult: DATETIME (3:45)HOUR TO MINUTE

INTERVAL (5-3) YEAR TO MONTH + 15 UNITS MONTHresult: INTERVAL (6-06) YEAR TO MONTH

INTERVAL (100:30.0005) MINUTE(3) TO FRACTION(4) - 120 UNITS SECONDresult: INTERVAL (98:30.0005) MINUTE TO FRACTION(4)

In each of these cases, an amount of a single field is added to or subtractedfrom an INTERVAL or DATETIME value. Note that the second and third exam-ples produce the same results as before. This is because manipulating single-field INTERVAL values is identical to manipulating UNITS values of the sametype and amount. The UNITS keyword is simply an easy way to write suchINTERVAL values.

Multiplying or Dividing INTERVAL ValuesYou can multiply or divide INTERVAL values by a number. The number canbe an integer or a fraction. However, INTERVAL values cannot be expressedas a fraction of a field. All results are written only as integers. If there is aremainder from the calculation, it is ignored, and the result is truncated. Notethe following examples:

INTERVAL (13-5) YEAR TO MONTH / 2result: INTERVAL (6-8) YEAR TO MONTH

INTERVAL (15:30.0002) MINUTE TO FRACTION(4) * 2.5result: INTERVAL (38:45.0005) MINUTE TO FRACTION(4)

The results of any calculation include the same amount of precision as theoriginal INTERVAL value. In the first example, the YEAR value is divided bytwo leaving one year as a remainder. This remainder is converted into 12months, added to the 5 existing months, and then divided. One month is leftover, but there is no lower precision, so this remainder is simply discarded inthe final result of 6 years and 8 months.

J-14 Working with DATETIME and INTERVAL Data

Page 811: Manual Informix

Data Manipulation Statements

The second example multiplies an INTERVAL by a fraction. In this case,15 * 2.5 = 37.5 minutes, 30 * 2.5 = 75 seconds, and 2 * 2.5 = 5 fraction(4). The.5 minute is converted into 30 seconds and 60 seconds are converted into 1minute, which produces the final result of 38 minutes, 45 seconds, and .0005of a second.

Data Manipulation StatementsYou can use DATETIME and INTERVAL values in any place that is appropriatefor other data types. Frequently, you might use these values in the context ofan SQL data manipulation statement, namely INSERT, UPDATE, DELETE,SELECT, LOAD, or UNLOAD.

In a previous section, you saw how you can use DATETIME and INTERVALvalues in an INSERT statement. The following examples illustrate how youcan use these values in other types of SQL data manipulation statements.

CREATE TABLE mytable(mytime DATETIME YEAR TO DAY, myval INTERVAL DAY TO SECOND)

UPDATE mytable SET myval = myval + INTERVAL (1 1:1:1) DAY TO SECOND

DELETE FROM mytable WHERE mytime < CURRENT - 1 UNITS YEAR

SELECT * FROM mytable WHERE mytime BETWEENDATETIME(88-7-1) YEAR TO DAY and DATETIME (89-6-30) YEAR TO DAY

SELECT mytime, mytime + INTERVAL (45) DAY TO DAY from mytable

The first example updates all rows by a constant INTERVAL value. The sec-ond example deletes the rows that are more than a year old. The third exam-ple selects all rows for a given one-year period. The final example includes aderived field in the select-list so that you can compare the existing date witha later one.

DATETIME and DATE CompatibilityThe database engine attempts to make appropriate data type conversionswhen they are required. For most situations, this allows you to use aDATETIME value wherever it is appropriate to use a DATE value and viceversa.

Working with DATETIME and INTERVAL Data J-15

Page 812: Manual Informix

DATETIME and DATE Compatibility

You can use DATE values in arithmetic expressions with DATETIME orINTERVAL values. You can write expressions that allow the followingmanipulations:

DATE - DATETIME result is INTERVALDATETIME - DATE result is INTERVALDATE +/- INTERVAL result is DATETIME

In these cases, DATE values are first converted to their correspondingDATETIME equivalents, and then the expression is computed in the normalway. In such expressions, you can also use TODAY, CURRENT, and UNITS torepresent DATE, DATETIME, and INTERVAL values, respectively.

Note: Expressions of the form DATE - DATE evaluate to a positive or negativeINTEGER value, corresponding to the number of days between the two dates. If anINTERVAL value is required, you must perform the data type conversion explicitlywith built-in functions.

For example, the following expression uses the DATE( ) function to convert characterstring constants to DATE values, calculates their difference, and then uses the UNITSDAY keywords to convert the INTEGER result to an INTERVAL value:

(DATE("5/2/89") - DATE("4/6/54")) UNITS DAYresult: INTERVAL (12810) DAY(5) TO DAY

If you need YEAR TO MONTH precision, you can use the EXTEND function on thefirst DATE operand, as in the next example:

EXTEND(DATE("5/2/89"), YEAR TO MONTH) - DATE("4/6/54")result: INTERVAL (35-01) YEAR TO MONTH

While you can interchange DATE and DATETIME values in many situations,it must be clear whether a value is a DATE or a DATETIME. A DATE value cancome from any of the following sources:

• a column name or program variable of type DATE

• the TODAY keyword

• the DATE( ) function

A DATETIME value can come from any of the following sources:

• a column name or program variable of type DATETIME

• the CURRENT keyword

• the EXTEND( ) function

• a DATETIME literal

J-16 Working with DATETIME and INTERVAL Data

Page 813: Manual Informix

DATETIME and DATE Compatibility

You can also represent DATE and DATETIME values as quoted characterstrings. You can only use strings that are in proper DATE or DATETIME for-mat, however, and only in contexts where the corresponding data type of thestring is known. The following examples illustrate what string format isrequired in various contexts:

DATE ("date-string")WHERE TODAY > "date-string"WHERE DATE-column < "date-string"

EXTEND ("datetime-string" [, qualifier])WHERE DATETIME-column > "datetime-string"

When a DATE value is expected, the string must be in DATE format; when aDATETIME value is expected, the string must be in DATETIME format. Forexample, you can use the string "10/30/1989" as a date-string but not as adatetime-string. Instead, you must use "1989-10-30" or "89-10-30" as thedatetime-string.

Working with DATETIME and INTERVAL Data J-17

Page 814: Manual Informix

DATETIME and DATE Compatibility

J-18 Working with DATETIME and INTERVAL Data

Page 815: Manual Informix

ErrorMessages

Error MessagesThis section contains the text of error messages that mayappear when you work with INFORMIX-4GL and suggestscorrective actions.

All errors include an error number. Use the error number toquickly locate the message in this section. Error messageswith negative numbers appear in order, starting with -100.The few error messages with positive numbers are placedat the back of the section.

Note: Unless otherwise noted, the statement containing theerror was not processed.

-100 Description of Error: ISAM error: there is already a recordwith the same value in a unique key.

Corrective Action: Check that you did not attempt to adda duplicate value to a column with a unique index viaiswrite, isrewrite, isrewcurr, or isaddindex.

-101 Description of Error: ISAM error: file is not open.

Corrective Action: Check that the ISAM file has beenopened using the isopen call, or that you have not tried towrite to a ISAM file opened for read only.

-102 Description of Error: ISAM error: illegal argument toISAM function.

Corrective Action: Check that one of the arguments to theISAM call is not outside of the range of acceptable valuesfor that argument.

Page 816: Manual Informix

-103 Description of Error: ISAM error: illegal key descriptor (too many parts ortoo long).

Corrective Action: Check that one or more of the elements that make up thekey description is not outside of the range of acceptable values for that ele-ment. (There is a maximum of 8 parts and 120 characters to each keydescriptor.)

-104 Description of Error: ISAM error: too many files open.

Corrective Action: The maximum number of files that can be open at onetime would be exceeded if this request were processed. Reduce the numberof open files by breaking your program up into two or more parts. The max-imum number of open files per process is 20.

-105 Description of Error: ISAM error: bad ISAM file format.

Corrective Action: The format of the ISAM file has been corrupted. Run thebcheck utility on the file, and it will try to repair damaged indexes. If bcheckcannot repair the file, you will need to reload your data from a backupmedium.

-106 Description of Error: ISAM error: non-exclusive access.

Corrective Action: You must first open the file with exclusive access whenyou add or delete an index.

-107 Description of Error: ISAM error: record is locked.

Corrective Action: The record or file requested by this call cannot beaccessed because it has been locked by another user. Wait a moment and re-enter your request.

If you are certain that the table is not in use and your system usestablename.lok files, you may need to empty the contents of this file. (This filecontains information about which rows of the table are being used at any onetime. It is normally emptied when a user finishes accessing the table. On occa-sion, the file is not emptied and, as a result, no one will be able to use thetable.) You can copy the ‘‘file’’ /dev/null into this file to remove all locks onrows in the table. Contact your System Administrator about this action.

-108 Description of Error: ISAM error: key already exists.

Corrective Action: You have attempted to add an index that previously hasbeen defined. You will need to delete this existing index before defininganother.

2 Error Messages

Page 817: Manual Informix

-109 Description of Error: ISAM error: the key is the file’s primary key.

Corrective Action: An attempt was made to delete the primary key column.The primary key cannot be deleted by the isdelindex call.

-110 Description of Error: ISAM error: end or beginning of the file.

Corrective Action: The beginning or end of the file was reached.

-111 Description of Error: ISAM error: no record found.

Corrective Action: No record could be found that contained the requestedvalue in the specified position. Edit your request and re-enter.

-112 Description of Error: ISAM error: there is no current record.

Corrective Action: An attempt to access a record in the current list has beenmade, but there is no current list. You must first perform a query and obtaina current list.

-113 Description of Error: ISAM error: the file is locked.

Corrective Action: The table you wish to alter is currently being used byanother user in exclusive mode. Wait until the table is no longer being usedbefore entering your request.

If you are certain that the table is not in use, you should run the UNLOCKTABLE command to unlock the table. Also, if your system containstablename.lok files, you may need to empty the contents of this file. (This filecontains information about which rows of the table are being used at any onetime. It is normally emptied when a user finishes accessing the table. On occa-sion, the file is not emptied and, as a result, no one will be able to use thetable.) You can copy the ‘‘file’’ /dev/null into this file to remove all locks onrows in the table. Be certain no processes are accessing the locked table beforeemptying the tablename.lok file. Contact your System Administrator aboutthis action.

-114 Description of Error: ISAM error: the file name is too long.

Corrective Action: Reduce the filename length to ten or fewer characters.

-116 Description of Error: ISAM error: cannot allocate memory.

Corrective Action: Insufficient memory is available to run your request.(INFORMIX-4GL has run out of addressable data space.) You need to reducethe complexity of your statement or form.

Error Messages 3

Page 818: Manual Informix

-118 Description of Error: ISAM error: cannot read transaction log record.

Corrective Action: The transaction log record is corrupted and cannot beused. You should CLOSE the DATABASE, execute a START DATABASE WITHLOG IN statement, and backup the database.

-119 Description of Error: ISAM error: bad log record.

Corrective Action: The transaction log record is corrupted and cannot beused. You should CLOSE the DATABASE, execute a START DATABASE WITHLOG IN statement, and backup the database.

-120 Description of Error: ISAM error: cannot open log file.

Corrective Action: Check that the log file exists, that you are using the cor-rect pathname, and that you have operating system read and write permis-sions on the file.

-121 Description of Error: ISAM error: cannot write log file record.

Corrective Action: Check that you have operating system write permissionon the file and that sufficient disk space is available to add to the file.

-122 Description of Error: ISAM error: BEGIN WORK encountered in a databasewithout transactions.

Corrective Action: You can only use the BEGIN WORK statement in a data-base with transactions. Make sure that you have created or started the data-base with transactions.

-123 Description of Error: ISAM error: no shared memory.

Corrective Action: Check that the Database Administrator has set up theshared memory partition.

-124 Description of Error: ISAM error: no BEGIN WORK found.

Corrective Action: In a database that is not MODE ANSI, you must first exe-cute a BEGIN WORK statement before you can execute a COMMIT WORK orROLLBACK WORK statement.

-125 Description of Error: ISAM error: cannot use NFS.

Corrective Action: Do not attempt to access remote files on the networkusing NFS.

4 Error Messages

Page 819: Manual Informix

-126 Description of Error: ISAM error: bad row id

Corrective Action: Run bcheck (on INFORMIX-SE) to check and repair indexstructures. Run tbcheck (on INFORMIX-OnLine) to check and repair indexand data structures.

-127 Description of Error: ISAM error: no primary key.

Corrective Action: Run bcheck to determine the source of the problem.Repair your table if necessary.

-128 Description of Error: ISAM error: no logging.

Corrective Action: You have attempted to execute a statement that requireslogging. Start your database with transactions and reexecute the statement.

-129 Description of Error: ISAM error: too many users.

Corrective Action: The shared memory parameter for the maximum num-ber of users was exceeded. Either ask your System Administrator to adjustthe parameter, or try the statement again later.

-130 Description of Error: ISAM error: dbspace not found.

Corrective Action: Check the name of your dbspace. Run the DB-Monitor toview existing dbspaces.

-131 Description of Error: ISAM error: no free disk space.

Corrective Action: There is not enough contiguous disk space to completethe operation. Consult your System Administrator for assistance.

-132 Description of Error: ISAM error: the row size is too big.

Corrective Action: Make the fields of the table smaller or create multipletables with fewer fields.

-133 Description of Error: ISAM error: audit trail exists.

Corrective Action: You cannot cluster a file with an audit trail. If you wantto cluster the file, you must first drop the audit trail.

-134 Description of Error: ISAM error: no more locks.

Corrective Action: The shared memory parameter for the maximum num-ber of locks was exceeded. Either lock the entire table, wait until more locksare available, or ask your System Administrator to adjust the parameter.

Error Messages 5

Page 820: Manual Informix

-135 Description of Error: ISAM error: tblspace does not exist

Corrective Action: Check whether the tblspace number is correct. (INFOR-MIX-OnLine)

-136 Description of Error: ISAM error: no more extents

Corrective Action: Use the DB-Monitor to add more disk space. (INFOR-MIX-OnLine)

-137 Description of Error: ISAM error: chunk table overflow

Corrective Action: There are too many chunks in the dbspace. ReinitializeINFORMIX-OnLine to allow for more chunks. (INFORMIX-OnLine)

-138 Description of Error: ISAM error: dbspace table overflow

Corrective Action: There are too many dbspaces. Reinitialize INFOR-MIX-OnLine to allow for more dbspaces. (INFORMIX-OnLine)

-139 Description of Error: ISAM error: logfile table overflow

Corrective Action: There are too many logfiles. Reinitialize INFOR-MIX-OnLine to allow for more logfiles. (INFORMIX-OnLine)

-141 Description of Error: ISAM error: tblspace table overflow

Corrective Action: There are too many tblspaces currently in use. Wait andtry later or reinitialize INFORMIX-OnLine to allow for more tblspaces.(INFORMIX-OnLine)

-142 Description of Error: ISAM error: overflow of tblspace page

Corrective Action: The keys for the table are too large for a page. Reduce thesize of the indexes. (INFORMIX-OnLine)

-143 Description of Error: ISAM error: deadlock detected

Corrective Action: A deadlock has occurred. Rollback the current transac-tion and retry it.

-144 Description of Error: ISAM error: key value locked

Corrective Action: Wait and retry action. (INFORMIX-OnLine)

-145 Description of Error: ISAM error: system does not have disk mirroring

Corrective Action: If you are trying to mirror a dbspace, first reinitializeINFORMIX-OnLine with a mirror for the root dbspace, then mirror otherdbspaces. (INFORMIX-OnLine)

6 Error Messages

Page 821: Manual Informix

-146 Description of Error: ISAM error: the other copy of this disk is currently dis-abled or non-existent.

Corrective Action: Bring up the other chunk of the mirror pair before youbring down this chunk. (INFORMIX-OnLine)

-147 Description of Error: ISAM error: archive in progress.

Corrective Action: Check that the action you are taking is compatible witharchiving. You cannot add a log or mirror a dbspace which contains a log ifan archive is in progress. (INFORMIX-OnLine)

-148 Description of Error: ISAM error: dbspace is not empty

Corrective Action: Drop all tables from a dbspace before trying to remove it.(INFORMIX-OnLine)

-149 Description of Error: ISAM error: INFORMIX-OnLine daemon is no longerrunning (INFORMIX-OnLine)

Corrective Action: You may have killed the OnLine daemon by accidentallykilling the wrong process. You must reinitialize INFORMIX-OnLine.

-200 Description of Error: Identifier is too long.

Corrective Action: Identifiers must be 18 characters or less. Select a newidentifier of the appropriate length.

-201 Description of Error: A syntax error has occurred.

Corrective Action: Check that you have not misspelled an SQL statement,placed key words out of sequence, or included an INFORMIX-4GL reservedword in your query.

-202 Description of Error: An illegal character has been found in the statement.

Corrective Action: Remove the illegal character (often a non-printable con-trol character) and resubmit the statement.

-203 Description of Error: An illegal integer has been found in the statement.

Corrective Action: Integers must be whole numbers from -2,147,483,647 to2,147,483,647. Check that you have not included a number with a fractionalportion or a number outside of the range of acceptable whole numbers.Check also that you have not inadvertently entered a letter in place of a num-ber (for example, 125p3 instead of 12503 ).

Error Messages 7

Page 822: Manual Informix

-204 Description of Error: An illegal floating-point number has been found in thestatement.

Corrective Action: Check that you have not inadvertently entered a letter inplace of a number (for example, 125b3 in place of 12503 ).

-205 Description of Error: Cannot use ROWID for views.

Corrective Action: Restructure your statement so that the virtual column isnot used in defining the view.

-206 Description of Error: The specified table name is not in the database.

Corrective Action: Check the spelling of the table name in your statement.Check the systables system catalog for a list of all database tables.

-207 Description of Error: Cannot update cursor declared on more than onetable.

Corrective Action: Check that you have not attempted to use a FOR UPDATEclause with cursors on multiple tables. Restructure your update statement,perhaps using multiple cursors.

-208 Description of Error: Memory allocation failed during query processing.

Corrective Action: Reduce the complexity of your query or program.

-209 Description of Error: Incompatible database format.

Corrective Action: You are attempting to use INFORMIX-4GL with a data-base built by INFORMIX-SQL or INFORMIX-ESQL/C 1.1. You must first rundbupdate on your database, which will prepare the database for INFOR-MIX-4GL.

-210 Description of Error: Pathname too long.

Corrective Action: INFORMIX-4GL will accept a pathname of up to 70 totalcharacters. Reduce the length of the pathname.

8 Error Messages

Page 823: Manual Informix

-211 Description of Error: Cannot read system catalog catalog-name.

System Action: See below for a list of system actions.

Corrective Action: Check the ISAM error for information about the source ofthe problem. Depending upon the content of the statement and the systemcatalog cited in the error message, the following actions have occurred:

For a CREATE TABLE statement: the systabauth catalog was not read, thetable was created, but no authorizations are granted to PUBLIC.

For a DROP TABLE statement: if the systables catalog was not read, then noaction was taken; if the sysviews catalog was not read, then the table wasdropped, but any views built on the table might not have been dropped.

For a DROP VIEW statement: the sysviews catalog was not read, and no actionwas taken.

For a DROP INDEX statement: the sysindexes or systables catalogs was notread, and the index was not dropped.

For a DROP SYNONYM statement: the systables catalog was not read (for tab-type = S), and the synonym was not dropped.

For a DROP DATABASE statement: the systables catalog was not read, and thedatabase was not dropped.

For a START DATABASE statement: the systables catalog was not read, andthe database was not started.

For a DATABASE statement: the systables or sysusers catalog was not read,and the database was not selected.

-212 Description of Error: Cannot add index.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-213 Description of Error: Statement interrupted by user.

Corrective Action: INFORMIX-4GL has received an interrupt signal(probably due to the user pressing the DEL or CTRL-C key). Resubmityour statement.

Error Messages 9

Page 824: Manual Informix

-214 Description of Error: Cannot remove file for table tablename.

System Action: If this is a DROP DATABASE statement, then some tables mayhave been dropped from the database. If this is a DROP TABLE statement,then some system entries for the table may have been dropped from thedatabase.

Corrective Action: INFORMIX-4GL cannot remove one or more of the entriesin the system catalogs for the table. Check the ISAM error for informationabout the source of the problem. Check with the System Administrator aboutremedial actions.

-215 Description of Error: Cannot open file for table tablename.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-216 Description of Error: Cannot remove ISAM index on file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-217 Description of Error: Column column-name not found in any table in thequery.

Corrective Action: Correct the spelling of the column name or that column-name exists in database table. Check for the presence of required commas andquotes.

-218 Description of Error: Synonym name not found.

Corrective Action: Check the spelling of the synonym. If needed, check thesystables system catalog (where tabtype = S) for a list of the current syn-onyms for table names.

-219 Description of Error: Wildcard matching cannot be used with non-charactertypes.

Corrective Action: Wildcards ( *, ?) and characters enclosed in brackets [ ]can be used only with CHAR data types. Check the data type for the offendingcolumn.

-220 Description of Error: There is no FROM clause in the query.

Corrective Action: Must include a FROM clause in the query. Check that youdo not have an illegal character ($, #, &, etc., or a CONTROL character) in theline prior to the FROM keyword.

10 Error Messages

Page 825: Manual Informix

-221 Description of Error: Cannot build temporary file for new table table-name.

Corrective Action: ISAM cannot access the temporary directory (usually,/tmp) or the disk may be out of space. Check the ISAM error for informationabout the source of the problem.

-222 Description of Error: Cannot write to temporary file for new table table-name.

Corrective Action: The disk may be out of space. Check the ISAM error forinformation about the source of the problem.

-223 Description of Error: Duplicate table name table-name in the FROM clause.Use an alias to rename one of the tables.

-224 Description of Error: Cannot open log file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-225 Description of Error: Cannot create file for system catalog catalog-name.

System Action: The CREATE DATABASE statement was not completed.Some system catalogs may have been created.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-226 Description of Error: Cannot create index for system catalog catalog-name.

System Action: The CREATE DATABASE statement was not completed.Some system catalogs may have been created.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-227 Description of Error: Cannot use ORDER BY clause when selecting into tem-porary table.

Corrective Action: Remove the ORDER BY clause from your statement. Placean index on the column you wish to order by after creating the temporarytable.

-228 Description of Error: Cannot have negative characters.

Corrective Action: Check that you have not included a negative CHAR datatype (for example, a -a or -p) in your statement.

Error Messages 11

Page 826: Manual Informix

-229 Description of Error: Could not open or create a temporary file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-230 Description of Error: Could not read a temporary file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-231 Description of Error: Cannot perform aggregate function with distinct onexpression.

Corrective Action: Select the expression into a temporary table and then per-form an aggregate distinct on the temporary table.

-232 Description of Error: A SERIAL column column-name cannot be updated.

Corrective Action: The values appearing in a SERIAL column are providedby INFORMIX-4GL and cannot be updated.

-233 Description of Error: Cannot read record that is locked by another user.

Corrective Action: Another user has locked the record. Wait a moment andre-enter your request.

-234 Description of Error: Cannot insert into virtual column column-name.

Corrective Action: The specified column is derived from an expression or anaggregate function. Redefine the view.

-235 Description of Error: Character column size is too big.

Corrective Action: Redefine the size of the column to 32,511 charactersor less.

-236 Description of Error: Number of columns in INSERT does not match numberof VALUES.

Corrective Action: Check that the number of columns in the table or in thecolumn list matches the number of values in the VALUES clause or theSELECT clause.

-237 Description of Error: Cannot begin work.

Corrective Action: Check the ISAM error number for information about thesource of the problem. Contact your System Administrator or DatabaseAdministrator if you need assistance with interpreting the ISAM error num-ber.

12 Error Messages

Page 827: Manual Informix

-238 Description of Error: Cannot COMMIT WORK.

Corrective Action: Your log file might be corrupted. Check the ISAM errornumber for information about the source of the problem. Contact your Sys-tem Administrator or Database Administrator if you need assistance withinterpreting the ISAM error number.

-239 Description of Error: Could not insert new row—duplicate value in aUNIQUE INDEX column.

Corrective Action: The row contains a value which already exists in the col-umn (indexed as unique) of an existing row. Enter a new value for the columnor remove the unique index on the column.

-240 Description of Error: Could not delete a row.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-241 Description of Error: Cannot ROLLBACK WORK.

Corrective Action: Check the ISAM error number for information about thesource of the problem. Contact your System Administrator or DatabaseAdministrator if you need assistance interpreting the ISAM error number.

-242 Description of Error: Could not open database table table-name.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-243 Description of Error: Could not position within a table table-name.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-244 Description of Error: Could not do a physical-order read to fetch next row.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-245 Description of Error: Could not position within a file via an index.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-246 Description of Error: Could not do an indexed read to get the next row.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

Error Messages 13

Page 828: Manual Informix

-247 Description of Error: ROLLFORWARD database failed.

Corrective Action: Check the ISAM error for information about the source ofthe problem. Contact your System Administrator or Database Administratorif you need assistance with interpreting the meaning of the ISAM error.

-248 Description of Error: Value of the program variable in the WHERE clauseis NULL.

Corrective Action: Use IS [NOT] NULL for NULL operation or initialize theprogram variable.

-249 Description of Error: Virtual column must have explicit name.

Corrective Action: When selecting into a temporary table or creating a view,each temporary or view column based on an expression must be given aunique name. Check also that distinct names are provided.

-250 Description of Error: Cannot read record from file for update.

Corrective Action: The record might be locked by another user. Check theISAM error for information about the source of the problem.

-251 Description of Error: ORDER BY column number too big.

Corrective Action: The number of the column noted in your ORDER BY state-ment exceeds the total number of columns in the SELECT statement.

-252 Description of Error: Cannot get system information for table.

System Action: Some statistics might be updated.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-253 Description of Error: Identifier too long—maximum length is 18.

Corrective Action: Check the spelling or length of the table name.

-254 Description of Error: Too many or too few host variables given.

Corrective Action: Check that the number of program variables in the fetchis equal to the number used when defining the cursor.

-255 Description of Error: Not in transaction.

Corrective Action: The statement must be executed within a transaction.First start a transaction, then perform the statement.

14 Error Messages

Page 829: Manual Informix

-256 Description of Error: Transaction not available.

Corrective Action: INFORMIX-4GL cannot perform a transaction operation(BEGIN WORK, ROLLBACK WORK, COMMIT WORK) on the database becausea transaction log was never created for the database. Ask your DatabaseAdministrator to create a transaction log for the database.

-257 Description of Error: System limit on cursors exceeded, maximum is num.

Corrective Action: Reduce the number of cursors used in the program.

-258 Description of Error: System error—invalid statement ID received by thesqlexec process.

Corrective Action: Make sure that the cursor or object is defined after theDATABASE statement. Contact the Informix Technical Support Department ifyou need additional assistance.

-259 Description of Error: Cursor not open.

Corrective Action: First open a cursor, then attempt the fetch.

-260 Description of Error: Cannot execute a SELECT statement that isPREPARED—must use cursor.

Corrective Action: Use a cursor for the SELECT statement.

-261 Description of Error: Could not create file for table table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-262 Description of Error: There is no current cursor.

Corrective Action: You cannot perform an UPDATE or DELETE action whenno current row exists. First perform a fetch, then attempt this action.

-263 Description of Error: Could not lock row for UPDATE.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-264 Description of Error: Could not write to a temporary file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

Error Messages 15

Page 830: Manual Informix

-265 Description of Error: Load or insert cursors must be run within atransaction.

Corrective Action: On databases with transactions, you must execute aBEGIN WORK statement before using an insert cursor.

-266 Description of Error: There is no current row for UPDATE/DELETE cursor.

Corrective Action: You cannot perform an UPDATE or DELETE action whenno current row exists. First perform a fetch, then attempt this action.

-267 Description of Error: The cursor has been previously released and isunavailable.

Corrective Action: Make sure that the cursor is open before you makereference to it.

-268 Description of Error: Cannot use SELECT DISTINCT with UNION ALL.

Corrective Action: Rewrite your statement.

-269 Description of Error: Cannot add column column-name that does notaccept nulls.

Corrective Action: Rewrite your statement.

-270 Description of Error: Could not position within a temporary file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-271 Description of Error: Could not insert new row into the table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-272 Description of Error: No SELECT permission.

Corrective Action: Request permission to SELECT from the owner of thetable.

-273 Description of Error: No UPDATE permission.

Corrective Action: Request permission to UPDATE from the owner of thetable.

-274 Description of Error: No DELETE permission.

Corrective Action: Request permission to DELETE from the owner of thetable.

16 Error Messages

Page 831: Manual Informix

-275 Description of Error: No INSERT permission.

Corrective Action: Request permission to INSERT from the owner of thetable.

-276 Description of Error: Cursor not found.

Corrective Action: You have called for a cursor that has not been declared inthe current session. (The current session runs from the issuance of a DATA-BASE statement to a CLOSE DATABASE statement, or the issuance of the nextDATABASE statement.) Declare your cursor within the current (database)session.

-277 Description of Error: UPDATE table table-name is not the same as the cursortable.

Corrective Action: Either declare a cursor on the table used in the UPDATEstatement, or update the table used in the cursor. Check the spelling of thetable name and cursor name.

-278 Description of Error: Too many ORDER BY columns.

Corrective Action: Reduce the number of columns included in the ORDERBY clause to 8 or less.

-279 Description of Error: Cannot GRANT or REVOKE database privileges fortable or view.

Corrective Action: Database privileges (CONNECT, RESOURCE, and DBA)cannot be granted on individual tables.

-280 Description of Error: A quoted string exceeds 256 bytes.

Corrective Action: Reduce the string to fewer than 256 characters.

-281 Description of Error: Could not add index to a temporary table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-282 Description of Error: Found a quote for which there is no matching quote.

Corrective Action: Check that all quoted strings are properly terminatedwith a quote.

-283 Description of Error: Found a non-terminated comment (‘‘{’’ with nomatching ‘‘}’’).

Corrective Action: Check that all comments are properly enclosed in braces.(Comments cannot be nested.)

Error Messages 17

Page 832: Manual Informix

-284 Description of Error: A subquery has returned not exactly one row.

Corrective Action: Restructure the subquery by adding more components tothe WHERE clause so that only one row is returned.

-285 Description of Error: Invalid cursor received by sqlexec.

Corrective Action: First issue a PREPARE statement within the current ses-sion, then re-enter your original statement.

-286 Description of Error: An expression cannot include ANY or ALL.

Corrective Action: ANY and ALL can only be used in association with asubquery.

-287 Description of Error: Cannot add SERIAL column column-name to the table.

Corrective Action: A SERIAL column does not accept NULL values. Add thecolumn to the table as type INTEGER, UPDATE it so that there are no NULLS,and then MODIFY it to type SERIAL.

-288 Description of Error: Table table-name not locked by current user.

Corrective Action: You cannot unlock a table locked by another user. Onlythe user who locked the table (or the DBA) can unlock the table.

-289 Description of Error: Cannot lock table table-name in share mode.

Corrective Action: The table is already locked in exclusive mode. Wait untilthe table is unlocked before reexecuting your request.

-290 Description of Error: Cursor not declared with FOR UPDATE clause.

Corrective Action: You must first declare a cursor with FOR UPDATE if thecursor is used for updating the database.

-291 Description of Error: Table table-name is already locked.

Corrective Action: You must first unlock the table before executing yourrequest.

-292 Description of Error: An implied INSERT column column-name does notaccept NULLs.

Corrective Action: INFORMIX-4GL will not allow you to insert a NULL valuein a column that does not allow NULLS. Check to see if a non-NULL columnis included in the column list in the INSERT statement.

18 Error Messages

Page 833: Manual Informix

-293 Description of Error: IS [NOT] NULL predicate may be used only withsimple columns.

Corrective Action: Restructure your query.

-294 Description of Error: The column column-name must be in the GROUP BY list.

Corrective Action: All non-aggregate columns in the SELECT list must beincluded in the GROUP BY list. Restructure your statement to include all col-umns that are not aggregate functions.

-295 Description of Error: The GROUP BY column number is too large.

Corrective Action: The number of the column noted in your GROUP BYstatement exceeds the total number of columns in the SELECT statement.

-297 Description of Error: The SELECT list may not contain a subquery.

Corrective Action: Remove the subquery from the SELECT list in thestatement.

-298 Description of Error: COUNT( [DISTINCT] colname ) may be used only witha simple column.

Corrective Action: You cannot include expressions within theCOUNT([DISTINCT] ... ) function. Restructure the query.

-299 Description of Error: A query may not contain more than one DISTINCT.

Corrective Action: Restructure your query to include only one DISTINCT.

-300 Description of Error: There are too many GROUP BY columns.

Corrective Action: The maximum number of columns in a GROUP BY clauseis 8. Reduce the number of columns in the statement to 8 or less.

-301 Description of Error: The total size of the GROUP BY columns is too big.

Corrective Action: The total number of characters in all columns listed in theGROUP BY list exceeds 120 characters. Reduce the column list.

-302 Description of Error: No GRANT option or illegal option on multi-tableview.

Corrective Action: You do not have permission to grant access privileges tothe table. Only the table owner, DBA, or a user with GRANT permission cando this.

Error Messages 19

Page 834: Manual Informix

-303 Description of Error: Expression mixes columns with aggregates.

Corrective Action: Restructure your query so that columns and aggregatesare not included in the same expression.

-304 Description of Error: HAVING can only have expressions with aggregates orcolumns in GROUP BY clause.

Corrective Action: Make sure that your HAVING clause contains either col-umns that are in the GROUP BY clause or expressions with aggregates.

-305 Description of Error: Subscripted column column-name is not of type CHAR,VARCHAR, TEXT nor BYTES.

Corrective Action: Verify that all subscripted columns are of type CHAR,VARCHAR, TEXT, or BYTE.

-306 Description of Error: Subscript out of range.

Corrective Action: The range of the subscript delimiter exceeds the range ofthe column data type. Check the size of the data type and reduce the sub-script range.

-307 Description of Error: Illegal subscript definition.

Corrective Action: Check that you have not reversed the order of the sub-script delimiters ([3,8] is a valid subscript; [8,3] is invalid) or included a neg-ative number as a subscript delimiter.

-308 Description of Error: Column type must be the same for each UNIONstatement.

Corrective Action: Check that each column in the UNION statement is of thesame data type.

-309 Description of Error: ORDER BY column column-name must be in SELECT list.

Corrective Action: Check that columns included in the ORDER BY clauseappear in the SELECT list.

-310 Description of Error: Table table-name already exists in database.

Corrective Action: Select an alternate name for the table.

-311 Description of Error: Cannot open system catalog catalog-name.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

20 Error Messages

Page 835: Manual Informix

-312 Description of Error: Cannot update system catalog catalog-name.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-313 Description of Error: Not owner of table table-name.

Corrective Action: Only the owner of the table (or the Database Administra-tor) can remove the table.

-314 Description of Error: Table table-name currently in use.

Corrective Action: The table you wish to drop is currently being used byanother user. Wait until the table is no longer being used before executingyour request.

-315 Description of Error: No CREATE INDEX permission.

Corrective Action: Permission not granted for you to create an index onthe table.

-316 Description of Error: Index index-name already exists in database.

Corrective Action: An index currently exists for the table. You must drop theexisting index before creating a new one.

-317 Description of Error: Must have the same number of selected columns ineach UNION statement.

Corrective Action: Check the number of columns selected in each SELECTstatement.

-318 Description of Error: File with the same name as specified log file alreadyexists.

Corrective Action: Select a different name for the log file.

-319 Description of Error: Index does not exist in database file.

Corrective Action: Check the spelling of the index name or check the sysin-dexes system catalog for the correct index name.

-320 Description of Error: Not owner of index index-name.

Corrective Action: Only the owner of the index (or the Database Adminis-trator) can remove the index.

-321 Description of Error: Cannot group by aggregate column.

Corrective Action: Check the column number used in the GROUP BY clause.

Error Messages 21

Page 836: Manual Informix

-322 Description of Error: Cannot alter view view-name.

Corrective Action: Views cannot be altered. You must drop and thenrecreate the view.

-323 Description of Error: Cannot grant permission on temporary table.

Corrective Action: Permissions can only be granted on permanent tables.

-324 Description of Error: Ambiguous column column-name.

Corrective Action: A column name exists in more than one table cited inyour query. Prefix each column name with the appropriate table name.

-325 Description of Error: Log file must be given a full pathname startingwith a ‘‘/’’.

Corrective Action: Provide the full pathname for the log file.

-326 Description of Error: Expecting CHAR type host variable.

Corrective Action: The cursor is on a CHAR column and your program isattempting to pass it a non-CHAR data type. Restructure your statement.

-327 Description of Error: Cannot unlock table tablename within a transaction.

Corrective Action: You cannot execute an UNLOCK TABLE statement withina transaction.

-328 Description of Error: Column column-name already exists in table.

Corrective Action: Select a new column name for the column.

-329 Description of Error: Database not found or no system permission.

Corrective Action: Check the spelling of the database name. Check that thedatabase name exists in your current directory or a directory included inyour DBPATH environment variable. Check the ISAM error for informationabout the source of the problem.

-330 Description of Error: Cannot create database.

Corrective Action: Check that you have not entered the name of an existingdatabase. Select an alternate name for the database. Check the ISAM error forinformation about the source of the problem.

22 Error Messages

Page 837: Manual Informix

-331 Description of Error: Cannot drop database directory.

System Action: All database files in the database directory are deleted, butthe directory remains.

Corrective Action: Remove any non-database files present in the databasedirectory, then remove the directory. Check the ISAM error for informationabout the source of the problem.

-332 Description of Error: Cannot access audit trail name information.

Corrective Action: Re-execute your request. If you again receive the error,the audit trail file has been corrupted. You may need to drop and restart theaudit trail.

-333 Description of Error: The audit trail file already exists with a different name.

Corrective Action: You must first drop the existing audit trail file (issue aDROP AUDIT statement) before creating a new audit trail.

-334 Description of Error: Cannot create audit trail.

Corrective Action: You must indicate the full pathname of the file receivingthe audit trail. Check that you have permission to write to a file in the selecteddirectory. Contact your System Administrator if you need help with thisaction.

-335 Description of Error: There is no audit trail for the specified table.

Corrective Action: INFORMIX-4GL is unable to recover the table as no audittrail was created.

-336 Description of Error: Cannot create or drop audit on temporary tabletable-name.

Corrective Action: You cannot place an audit trail on a temporary table.

-337 Description of Error: Cannot create view on temporary table table-name.

Corrective Action: You cannot create a view on a temporary table.

-338 Description of Error: Cannot drop audit trail.

Corrective Action: Re-execute your request. If the problem reoccurs, checkthe ISAM error message for information about the source of the problem.Contact your System Administrator if you require assistance with this action.

Error Messages 23

Page 838: Manual Informix

-339 Description of Error: The audit trail file name must be given in full directorypath.

Corrective Action: Edit your statement to include the full pathname of theaudit trail file.

-340 Description of Error: Cannot open audit trail file. (operating system error).

Corrective Action: Check that you have operating system read permissionto the file. Contact your System Administrator if you need help with thisaction.

-341 Description of Error: Could not read a row from audit trail file.

Corrective Action: The request was not completed (possible operating sys-tem error). Re-execute your request. If the problem reoccurs, check the ISAMerror message for information about the source of the problem. Contact yourSystem Administrator if you require assistance with this action. If you againreceive the error, the audit trail file has been corrupted. You may need to dropand restart the audit trail.

-343 Description of Error: Row from audit trail was added to a different positionthan expected.

Corrective Action: Re-execute your request. If the problem reoccurs, checkthe ISAM error message for information about the source of the problem.Contact your System Administrator if you require assistance with this action.If you again receive the error, the audit trail file has been corrupted. You mayneed to drop and restart the audit trail.

-344 Description of Error: Cannot delete row—row in table does not match rowin audit trail.

Corrective Action: Re-execute your request. If the problem reoccurs, checkthe ISAM error message for information about the source of the problem.Contact your System Administrator if you require assistance with this action.If you again receive the error, the audit trail file has been corrupted. You mayneed to drop and restart the audit trail.

-345 Description of Error: Cannot update row—row in table does not match rowin audit trail.

Corrective Action: Re-execute your request. If the problem reoccurs, checkthe ISAM error message for information about the source of the problem.Contact your System Administrator if you require assistance with this action.If you again receive the error, the audit trail file has been corrupted. You mayneed to drop and restart the audit trail.

24 Error Messages

Page 839: Manual Informix

-346 Description of Error: Could not update a row in the table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-347 Description of Error: Could not open table for exclusive access.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-348 Description of Error: Could not read a row from the table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-349 Description of Error: Database not selected yet.

Corrective Action: You must first select the database before executing astatement that refers to a database.

-350 Description of Error: Index already exists on column.

Corrective Action: Adding an index on the column is not necessary, as thecolumn is already indexed.

-351 Description of Error: Database contains tables owned by other users.

Corrective Action: You can only drop a database if you own all tables in thedatabase or have Database Administrator status. Contact your DatabaseAdministrator if you need help with this action.

-352 Description of Error: Column not found.

Corrective Action: Check the spelling of the column name.

-353 Description of Error: No table or view specified when granting or revokingtable privileges.

Corrective Action: You must include the name of the table or view on whicha privilege is granted or revoked in your SQL statement.

-354 Description of Error: Incorrect database or cursor name format.

Corrective Action: A database name must be ten characters or less. A cursorname must be 18 characters or less. A database or cursor name must beginwith a letter, and contain letters, numbers, or underscores. Check that youhave not included an illegal character in the name.

Error Messages 25

Page 840: Manual Informix

-355 Description of Error: Cannot rename file for table.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-356 Description of Error: Table table-name specified in both main query andsubquery.

Corrective Action: The statement is ambiguous because a column cannot beidentified uniquely. Use an alias to rename the offending table.

-357 Description of Error: Dependent table for view view-name has been altered.

Corrective Action: A table upon which the view is constructed has beenmodified (for example, a column has been dropped, a data type has beenmodified, or a column has been added to the middle of the table). Drop theview and create a new view.

-358 Description of Error: You must close the current database before youexecute CREATE, START, or ROLLFORWARD.

Corrective Action: You can only use the CREATE DATABASE, STARTDATABASE, and ROLLFORWARD DATABASE statements when there is nocurrent database. Execute a CLOSE DATABASE statement before executingone of these statements.

-359 Description of Error: Cannot drop current database.

Corrective Action: First execute a CLOSE DATABASE statement beforeexecuting a DROP DATABASE statement.

-360 Description of Error: Cannot modify table or view used in subquery.

Corrective Action: If allowed, your statement could reduce to a loopingprogram. Edit your statement.

-361 Description of Error: Column size too large.

Corrective Action: Reduce the size of the column. You cannot have a CHARcolumn larger than 32,511 characters.

-362 Description of Error: Can have only one column of SERIAL type.

Corrective Action: You cannot have more than one column of SERIAL typein a table. Select an alternate data type for the column.

-363 Description of Error: Cursor not on SELECT statement.

Corrective Action: Use EXECUTE to execute prepared objects on non-SELECTstatements.

26 Error Messages

Page 841: Manual Informix

-364 Description of Error: Column column-name not declared FOR UPDATE OF.

Corrective Action: Include the column in the FOR UPDATE OF list.

-365 Description of Error: Cursor must be on simple SELECT for FOR UPDATE.

Corrective Action: Check that the cursor does not include more than onetable or involve aggregates.

-366 Description of Error: The scale exceeds the maximum precision specified.

Corrective Action: The problem is located in a DECIMAL or MONEY column.The scale (number of digits to the right of the decimal point) exceeds the pre-cision (total number of digits). You must correct one of the followingconditions:

DECIMAL ( m, n) where n > mMONEY ( m, n) where n > mMONEY ( m) where m < 2

-367 Description of Error: Sums and averages cannot be computed for charactercolumns.

Corrective Action: Check that you have not included a column of a characterdata type in the aggregate function statement.

-368 Description of Error: Incompatible sqlexec module.

Corrective Action: Check that the correct version of sqlexec has beeninstalled. Contact your Database Administrator if you need help with thisaction.

-369 Description of Error: Invalid serial number. Please consult your installationinstructions.

Corrective Action: Check that the correct version of sqlexec has beeninstalled. Contact your Database Administrator if you need help with thisaction.

-370 Description of Error: Cannot drop last column.

Corrective Action: Only one column remains in the table. Use the DROPTABLE statement to remove the table.

-371 Description of Error: Cannot create unique index on column with duplicatedata.

Corrective Action: The column contains duplicate data.

Error Messages 27

Page 842: Manual Informix

-372 Description of Error: Cannot alter table with audit trail on.

Corrective Action: You must first drop the audit trail before making anychanges to the table. After making the changes, you may want to re-establishan audit trail.

-373 Description of Error: DBPATH too long.

Corrective Action: Reduce the length of your DBPATH environmentvariable.

-374 Description of Error: Can only use column number in ORDER BY clause withUNION.

Corrective Action: Restructure the query, using ordinal numbers for theORDER BY columns.

-375 Description of Error: Cannot create log file for transaction.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

-376 Description of Error: Log file already exists.

Corrective Action: Select an alternate name for the log file.

-377 Description of Error: Must terminate transaction before closing database.

Corrective Action: Issue a COMMIT WORK or ROLLBACK statement beforeclosing the database.

-378 Description of Error: Record currently locked by another user.

Corrective Action: Wait until the record is unlocked before submitting thestatement. Check the ISAM error for information about the source of theproblem.

-379 Description of Error: Cannot revoke privilege on columns.

Corrective Action: First revoke UPDATE or SELECT privilege on the table,then grant the revoked privileges.

-380 Description of Error: Cannot erase log file.

Corrective Action: Check the ISAM error for information about the source ofthe problem.

28 Error Messages

Page 843: Manual Informix

-381 Description of Error: Cannot grant to someone who has granted you thesame privilege before.

Corrective Action: The name of the individual who granted you permissionto use the table must be removed from your user list.

-382 Description of Error: Same number of columns must be specified for viewand select clause.

Corrective Action: Check the number of columns in the view definition andthe selected columns.

-383 Description of Error: View column for aggregate or expression must beexplicitly named.

Corrective Action: Provide a name for all virtual columns.

-384 Description of Error: Cannot modify non-simple view.

Corrective Action: Can only modify views built on a single table.

-385 Description of Error: Data value out of range.

Corrective Action: Check the view definition for valid data ranges.

-386 Description of Error: Column contains null values.

Corrective Action: The table contains NULL values in a column being alteredto disallow NULLS. Remove NULL values from the column.

-387 Description of Error: No connect permission.

Corrective Action: Contact the Database Administrator and requestCONNECT permission.

-388 Description of Error: No resource permission.

Corrective Action: Contact the Database Administrator and requestRESOURCE permission.

-389 Description of Error: No DBA permission.

Corrective Action: Contact the Database Administrator and request DBApermission.

-390 Description of Error: Synonym already used as table name or synonym.

Corrective Action: Select a different synonym that does not match the nameor synonym of any table or view in the current database. Check the systablessystem catalog (where tabtype = S) for a list of existing synonyms.

Error Messages 29

Page 844: Manual Informix

-391 Description of Error: Cannot insert a NULL into column column-name.

Corrective Action: Check that a column that does not allow NULL values isomitted from the insert column list.

-392 Description of Error: System error—unexpected NULL pointer encountered.

Corrective Action: Notify the Informix Technical Support Department.

-393 Description of Error: A condition in the where clause results in a two-sidedouter join.

Corrective Action: A two-sided outer join is not allowed. Restructure yourquery.

-394 Description of Error: View view-name not found.

Corrective Action: Check the spelling of the view name. Check the sysviewssystem catalog for a list of existing views.

-395 Description of Error: The where clause contains an outer cartesian product.

Corrective Action: Check the syntax of the statement.

-396 Description of Error: Illegal join between a nested outer table and a pre-served table.

Corrective Action: Check the syntax of the statement.

-397 Description of Error: System catalog corrupted.

Corrective Action: Contact the Database Administrator for help with thiserror.

-398 Description of Error: Cursor manipulation must be within a transaction.

Corrective Action: Perform a BEGIN WORK statement before any cursormanipulations.

-399 Description of Error: Cannot access log file.

Corrective Action: You cannot edit the log file.

-400 Description of Error: Fetch attempted on unopen cursor.

Corrective Action: Check that the cursor was properly opened using anOPEN CURSOR statement.

-401 Description of Error: Fetch attempted on NULL cursor.

Corrective Action: Check that the cursor was properly opened using anOPEN CURSOR statement.

30 Error Messages

Page 845: Manual Informix

-402 Description of Error: Address of a host variable is NULL.

Corrective Action: Check the addresses of each program variable (one ormore have a NULL value).

-403 Description of Error: The size of a received row disagrees with theexpected size.

Corrective Action: Check that you are using the proper library in theprogram.

-404 Description of Error: A NULL control block has been passed as an argument.

Corrective Action: Check that you are using the proper library in theprogram.

-405 Description of Error: The address of a host variable is not properly aligned.

Corrective Action: Check that each program variable is aligned with theproper address boundary for variables of that type.

-406 Description of Error: Memory allocation failed.

Corrective Action: Exit to the operating system command line, re-enter theprogram you were using, and resubmit your program.

-407 Description of Error: Error number zero received from the sqlexec process.

Corrective Action: Exit to the operating system command line, re-enter theprogram you were using, and resubmit your program.

-408 Description of Error: Invalid message type received from the sqlexecprocess.

Corrective Action: Exit to the operating system command line, re-enter theprogram you were using, and resubmit your program.

-409 Description of Error: sqlexec was not found or was not executable by thecurrent user.

Corrective Action: Check that your INFORMIXDIR environment variable isproperly set. Contact your System Administrator if you need help with thisaction.

-410 Description of Error: PREPARE statement failed or was not executed.

Corrective Action: Check that your PREPARE statement was successfullyexecuted (a failure is often due to a syntax error).

Error Messages 31

Page 846: Manual Informix

-412 Description of Error: Command pointer is NULL.

Corrective Action: The statement executed prior to the current statementreturned an error that was not trapped. Re-execute the prior statement(s) andinclude a response to the error code returned.

-413 Description of Error: Insert attempted on unopened cursor.

Corrective Action: You must first open the cursor before executing a PUTstatement.

-414 Description of Error: Insert attempted on NULL cursor.

Corrective Action: Make sure you have correctly declared the cursor forinsert. Check the error code returned from the DECLARE statement.

-415 Description of Error: Data conversion error discovered during PUToperation.

Corrective Action: The program variable is incompatible with the data typeof a column in the database. Choose an appropriate program variable orrestrict the size of the data in the program variable.

-416 Description of Error: USING option with open statement is invalid forinsert cursor.

Corrective Action: You should use the FROM option with the PUT statementor the USING option with the EXECUTE statement.

-417 Description of Error: FLUSH can only be used on an insert cursor.

Corrective Action: Make sure that you are using the correct cursor.

-420 Description of Error: Cannot execute remote sqlexec.

Corrective Action: Check the setting of the SQLHOST environment variable,that the sqlexec file exists on the specified node, or that the specified node isaccessible to you.

-421 Description of Error: Unknown service for execution of remote sqlexec.

Corrective Action: The /etc/services file does not contain an sql entry. Checkwith your System Administrator about adding the required entry.

-422 Description of Error: FLUSH attempted on unopened cursor.

Corrective Action: You must first open an insert cursor before executing theFLUSH statement.

32 Error Messages

Page 847: Manual Informix

-425 Description of Error: Database is currently opened by another user.

Corrective Action: Another user has an exclusive lock on the database. Waitfor the lock to be released, and then retry the operation.

-426 Description of Error: Unknown values have already been supplied.

Corrective Action: This is an internal error. Please notify the Informix Tech-nical Support Department.

-427 Description of Error: Bind count routine called with a different count.

Corrective Action: This is an internal error. Please notify the InformixTechnical Support Department.

-428 Description of Error: Bind routine called too many times.

Corrective Action: This is an internal error. Please notify the InformixTechnical Support Department.

-430 Description of Error: Type integer does not match size.

Corrective Action: This is an internal error. Please notify the InformixTechnical Support Department.

-431 Description of Error: Type float does not match size.

Corrective Action: This is an internal error. Please notify the InformixTechnical Support Department.

-432 Description of Error: Type date does not match size.

Corrective Action: This is an internal error. Please notify the Informix Tech-nical Support Department.

-433 Description of Error: Type money does not match size.

Corrective Action: This is an internal error. Please notify the Informix Tech-nical Support Department.

-434 Description of Error: Type decimal does not match size.

Corrective Action: This is an internal error. Please notify the Informix Tech-nical Support Department.

-450 Description of Error: Illegal ESQL locator, or uninitialized blob variable in4GL.

Corrective Action: An uninitialized BYTE or TEXT variable has been used ina context where an initialized variable is expected. Use the LOCATE state-ment to initialize the variable (INFORMIX-OnLine).

Error Messages 33

Page 848: Manual Informix

-451 Description of Error: Locator buffer too small

Corrective Action: Increase the size of the locator buffer or select only partof the BLOB using subscripts.

-452 Description of Error: ‘loc_open()’ failed

Corrective Action: The "loc_open" routine that you supplied returned anerror status. Verify that the function is correct or examine status informationthat it returns.

-453 Description of Error: ‘loc_close()’ failed

Corrective Action: The "loc_close" routine that you supplied returned anerror status. Verify that the function is correct or examine status informationthat it returns.

-454 Description of Error: ‘loc_read()’ failed

Corrective Action: The "loc_read" routine that you supplied returned anerror status. Verify that the function is correct or examine status informationthat it returns.

-455 Description of Error: ‘loc_write()’ failed

Corrective Action: The "loc_write" routine that you supplied returned anerror status. Verify that the function is correct or examine status informationthat it returns.

-456 Description of Error: Indicator value cannot fit in host variable.

Corrective Action: This is an internal error. Please notify the InformixTechnical Support Department.

-461 Description of Error: File open error.

Corrective Action: Verify that the file exists and that it has the correctpermissions.

-462 Description of Error: File close error.

Corrective Action: Verify that the file exists and that it has the correctpermissions.

-463 Description of Error: File read error.

Corrective Action: Verify that the file exists and that it has the correctpermissions.

34 Error Messages

Page 849: Manual Informix

-464 Description of Error: File write error.

Corrective Action: Verify that the file exists and that it has the correctpermissions.

-465 Description of Error: No more memory for locator buffer.

Corrective Action: Exit to the operating system command line and resubmityour program.

-500 Description of Error: Clustered index index-name already exists in the table.

Corrective Action: A table can have only one clustered index. You must firstalter the existing cluster index to NOT CLUSTER before creating a new clus-tered index.

-501 Description of Error: Index index-name is already not clustered.

Corrective Action: You do not need to alter the index to NOT CLUSTER.

-502 Description of Error: Cannot cluster index.

Corrective Action: Check the ISAM error code for more information aboutthe source of the problem.

-503 Description of Error: Too many tables locked.

Corrective Action: Either unlock one or more tables, or open the database inexclusive mode.

-504 Description of Error: Cannot lock a view.

Corrective Action: You cannot execute the LOCK TABLE command on aview.

-505 Description of Error: Number of columns in UPDATE does not match num-ber of VALUES.

Corrective Action: The number of columns in the UPDATE statement mustequal the number of values. Rewrite your SQL statement.

-506 Description of Error: Do not have permission to update all columns.

Corrective Action: Obtain permission from the owner of the table. You canquery the systables system catalog for this information.

-507 Description of Error: Cursor not found.

Corrective Action: This cursor has not been defined. Check the spelling ofcursor-name.

Error Messages 35

Page 850: Manual Informix

-508 Description of Error: Cannot rename a temporary table.

Corrective Action: Remove the RENAME TABLE statement from yourprogram.

-509 Description of Error: Cannot rename a column in a temporary table.

Corrective Action: Remove the RENAME COLUMN statement from yourprogram.

-510 Description of Error: Cannot create synonym for temporary tabletable-name.

Corrective Action: Remove the CREATE SYNONYM statement from yourprogram.

-511 Description of Error: Cannot modify system catalog catalog-name.

Corrective Action: You do not have alter permission on any of the systemcatalogs. Do not attempt to modify these files.

-512 Description of Error: Cannot open database database-name in exclusivemode.

Corrective Action: Another user is currently using the database. Wait untilthe database is no longer in use.

-513 Description of Error: Statement not available with this database engine.

Corrective Action: The statement that you used is not available with theINFORMIX-OnLine database engine.

-514 Description of Error: Only DBA can create, drop, or grant for another user.

Corrective Action: Ask the DBA to perform the operation for you, or togrant you DBA permission.

-515 Description of Error: Statement not available using non-INFORMIX-OnLinedatabase server.

Corrective Action: Make sure that you are using the appropriate databaseserver (sqlexec for INFORMIX-SE or sqlturbo for INFORMIX-OnLine).

-516 Description of Error: System error-temporary output file not yet created.

Corrective Action: Check the ISAM error for the source of the problem.

36 Error Messages

Page 851: Manual Informix

-517 Description of Error: The size of the index fields is too large or there are toomany parts in the index.

Corrective Action: Reduce the number of fields or the size of the fields inyour index.

-518 Description of Error: Cannot have extent size equal to zero.

Corrective Action: The extent size must be at least four pages.

-519 Description of Error: Cannot update column to illegal value.

Corrective Action: Check the values in your UPDATE or INSERT statement.

-520 Description of Error: Cannot open database tblspace.

Corrective Action: Check that the chunk that contains the tblspace is on-line.

-521 Description of Error: Cannot lock system catalog catalog-name.

Corrective Action: You are not allowed to lock system catalogs. Check thespelling of the table to be locked.

-522 Description of Error: Table table-name not selected in query.

Corrective Action: Check the spelling of the table in the query.

-523 Description of Error: You can only recover, repair, or drop a table.

Corrective Action: Check to make sure that the table in the query is not aview.

-524 Description of Error: Lock table can only be used within a transaction.

Corrective Action: You must start logging for the database before executingthe statement.

-525 Description of Error: Cannot create database—no system permission.

Corrective Action: Make sure you have write and execute permission on thecurrent directory.

-526 Description of Error: Updates are not allowed on a scroll cursor.

Corrective Action: Do not use a scroll cursor with a statement that isdeclared SELECT FOR UPDATE.

-527 Description of Error: Lock mode is not available on this system.

Corrective Action: Modify your program to not WAIT FOR LOCK.

Error Messages 37

Page 852: Manual Informix

-528 Description of Error: Maximum output rowsize (32767) exceeded.

Corrective Action: The total number of bytes for the selected columns isgreater than the maximum permitted. You should reduce the number ofitems in the select list. (INFORMIX-OnLine)

-529 Description of Error: Cannot attach to shared memory.

Corrective Action: The shared memory might not be up. Check the ISAMerror message for the specific reason.

-531 Description of Error: Duplicate column column-name exists in view.

Corrective Action: Two view columns have the same name; change one ofthem.

-532 Description of Error: Cannot alter temporary table table-name.

Corrective Action: A temporary table cannot be altered.

-533 Description of Error: Extent size too small, minimum size is size.

Corrective Action: You must enter a size that is at least four pages. Reenterthe statement specifying at least size kilobytes.

-534 Description of Error: Could not insert new row into table, table is locked.

Corrective Action: Wait until table is unlocked, and retry the statement.

-535 Description of Error: Already in transaction.

Corrective Action: You must issue a COMMIT WORK or ROLLBACK WORKstatement at this point.

-536 Description of Error: Cannot have more than one cursor on the samestatement.

Corrective Action: Prepare another identifier on the statement, and declarea cursor on that identifier.

-538 Description of Error: Cursor cursor-name has already been declared.

Corrective Action: Check to see where you have declared a cursor with thesame name elsewhere, and change one of the cursor names.

-539 Description of Error: DBTEMP too long.

Corrective Action: Shorten the pathname which you have assigned toDBTEMP, or use the default value.

38 Error Messages

Page 853: Manual Informix

-540 Description of Error: Write failed on constraints.

Corrective Action: Verify that you are not trying to give a UNIQUECONSTRAINT a name that has already been used in the database. You cancheck the sysconstraints table for existing UNIQUE CONSTRAINT names.

-541 Description of Error: User does not have ALTER privilege.

Corrective Action: To modify the name or schema of a table, you must haveALTER privilege on the table, or be the DBA, or be the owner of the table.

-542 Description of Error: Cannot specify the same column more than once in aUNIQUE constraint.

Corrective Action: Check your UNIQUE list definition to be sure that nocolumn is specified more than once in a composite UNIQUE CONSTRAINT.

-543 Description of Error: ESCAPE character must be only one character.

Corrective Action: Check your ESCAPE definition to verify that you haveonly specified one character as the ESCAPE character.

-544 Description of Error: Cannot have aggregates within aggregates.

Corrective Action: Do not nest aggregate statements.

-545 Description of Error: No write permission for table table-name.

Corrective Action: Use the UNIX chmod utility to add write permission onthe appropriate .dat file.

-546 Description of Error: Cannot have host variables when creating a view.

Corrective Action: Do not use host variables in a CREATE VIEW statement.

-549 Description of Error: Column column-name in UNIQUE constraint is not acolumn in the table.

Corrective Action: Verify that the column you are specifying exists in thetable. Check the spelling of the column name(s) specified in your UNIQUElist.

-550 Description of Error: Total length of columns in UNIQUE constraint is toolong.

Corrective Action: The maximum length for columns in a UNIQUECONSTRAINT is 120 bytes.

Error Messages 39

Page 854: Manual Informix

-551 Description of Error: UNIQUE constraint contains too many columns.

Corrective Action: The maximum number of columns in a UNIQUECONSTRAINT is 8.

-554 Description of Error: Syntax disallowed in this database engine.

Corrective Action: Check the syntax of your statement; you have usedINFORMIX-OnLine syntax on INFORMIX-SE.

-555 Description of Error: Cannot use a select or any of the database statementsin a multi-query prepare.

Corrective Action: You cannot specify the following statements in amulti-statement prepare:

CLOSE DATABASECREATE DATABASEDATABASEDROP DATABASESELECT

-556 Description of Error: Cannot create, drop, or modify a remote object.

Corrective Action: You can only read the contents of external tables. If youmake the database your current database, you can modify the contents.

-557 Description of Error: Cannot locate remote table after count levels ofsynonym mapping.

Corrective Action: You have used a synonym that points to a chain ofsynonyms, and the number of synonyms in the chain exceeds 16.

-559 Description of Error: Cannot create a synonym on top of another synonym.

Corrective Action: You can only create a synonym for a table or view. Checkthat the synonym name that you are trying to use is not the name of an exist-ing synonym. You can look at the systables table to find the names of existingsynonyms (where tabtype = S).

-560 Description of Error: Synonym with tabid name not found in systables.

Corrective Action: Your systables system catalog might be corrupted. Youmay need to rebuild the catalog.

-561 Description of Error: Sums and averages cannot be computed on datetimevalues.

Corrective Action: Do not attempt to use the SUM or AVG aggregate func-tions on a column of type DATETIME.

40 Error Messages

Page 855: Manual Informix

-562 Description of Error: Database conversion failed.

Corrective Action: When you opened your database for the first time withthis release, the creation of the new sytem tables failed for some reason otherthan locking.

This is an internal error. Read the ISAM error for more information. After ver-ifying that the error has not been generated as the result of a system limit orproblem, please record the actions that preceded this error and notify theInformix Technical Support Department.

-563 Description of Error: Cannot acquire exclusive lock for database conver-sion.

Corrective Action: Someone else might have an exclusive lock on the data-base, or someone else might be accessing the database. Wait to run the data-base conversion until no one else is accessing the database.

-564 Description of Error: Cannot sort rows.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

-565 Description of Error: Cannot read sorted rows.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

-566 Description of Error: Cannot initiate sort.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

-567 Description of Error: Cannot write sorted rows.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

Error Messages 41

Page 856: Manual Informix

-568 Description of Error: Cannot reference an external database withoutlogging.

Corrective Action: Because you are using a database with logging as yourcurrent database, you can only access remote databases that have logging.You have to turn logging on in the remote database in order to access it.

-569 Description of Error: Cannot reference an external database with logging.

Corrective Action: Because you are using a database without logging asyour current database, you can only access remote databases that do not havelogging. You have to turn logging on in your database in order to access theremote database.

-570 Description of Error: Cannot reference an external ANSI database.

Corrective Action: Because your current database is not MODE ANSI, youcan only access remote databases that are also not MODE ANSI.

-571 Description of Error: Cannot reference an external non-ANSI database.

Corrective Action: Because your current database is MODE ANSI, you canonly access remote databases that are also MODE ANSI.

-572 Description of Error: The specified wait duration is too long.

Corrective Action: The maximum wait duration for SET LOCK MODE TOWAIT is 32,767 seconds.

-573 Description of Error: Cannot set log to buffered in a mode ANSI database.

Corrective Action: If you choose to make your database MODE ANSI, it willhave unbuffered logging.

-574 Description of Error: A subquery has returned not exactly one column.

Corrective Action: A subquery (select statement within a WHERE clause)can only have a single column or expression in its select list. Modify the sub-query to contain a single column or expression.

-575 Description of Error: LENGTH( ) requires string type values.

Corrective Action: You can only use the LENGTH( ) function with charactercolumns.

42 Error Messages

Page 857: Manual Informix

-576 Description of Error: Cannot specify UNIQUE CONSTRAINT name for TEMPtable.

Corrective Action: You can specify a UNIQUE CONSTRAINT for a TEMPtable, but you cannot specify a name for the constraint. Remove theCONSTRAINT constr-name clause from your CREATE TEMP TABLE statement.

-577 Description of Error: UNIQUE constraint already exists on the column set.

Corrective Action: A UNIQUE CONSTRAINT was specified for this columnset when the table was created. Check the sysconstraints table for a list ofUNIQUE CONSTRAINTs for this table. (If your database is MODE ANSI,remember to prefix system catalog names with ‘‘informix’’.) Check the spell-ing of your UNIQUE CONSTRAINT name to verify that you are not using aname that is already assigned to a UNIQUE CONSTRAINT on this table.

-579 Description of Error: Not owner of synonym.

Corrective Action: To DROP a synonym, you must be the DBA or the ownerof the synonym.

-600 Description of Error: Cannot create blob.

Corrective Action: Verify that you are referring to a valid blobspace.

-601 Description of Error: Cannot delete blob.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-602 Description of Error: Cannot open blob.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-603 Description of Error: Cannot close blob.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

Error Messages 43

Page 858: Manual Informix

-604 Description of Error: Cannot read blob.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-605 Description of Error: Cannot write blob.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-606 Description of Error: Invalid blob space name.

Corrective Action: Check the name of the blobspace in which you are stor-ing the BLOB data to make certain that the blobspace exists.

-607 Description of Error: Text/Byte subscript error.

Corrective Action: Examine the subscripts used in the query to be certainthey are positive, less than or equal to the size of the BLOB, and that the firstis smaller than the second.

-608 Description of Error: Illegal attempt to convert Text/Byte blob type.

Corrective Action: BLOB types can only be selected into or created fromBLOB host variables.

-609 Description of Error: Illegal attempt to use Text/Byte host variable.

Corrective Action: BLOB host variables can only be used to select or createBLOB columns.

-610 Description of Error: Index not allowed on blob columns.

Corrective Action: You cannot place indexes on BLOB columns.

-611 Description of Error: Scroll cursor can’t select blob columns

Corrective Action: You cannot select BLOB columns with a scroll cursor.

-612 Description of Error: Blobs are not allowed in the "group by" clause.

Corrective Action: You cannot include a BLOB column in a GROUP BY clause;rewrite your select statement.

44 Error Messages

Page 859: Manual Informix

-613 Description of Error: Blobs are not allowed in the "distinct" clause.

Corrective Action: You cannot include a BLOB column in a DISTINCT clause;rewrite your SELECT statement.

-614 Description of Error: Blobs are not allowed in the "order by" clause.

Corrective Action: You cannot include a BLOB column in an ORDER BYclause; rewrite your SELECT statement.

-615 Description of Error: Blobs are not allowed in this expression.

Corrective Action: Verify that BLOBs are not being used in the COUNT, SUM,MIN, MAX, and AVG aggregate functions.

-616 Description of Error: A blob subscript is not allowed within this context.

Corrective Action: Verify that subscripted BLOB columns are not being usedas targets for the INSERT and UPDATE statements.

-617 Description of Error: A blob data type must be supplied within this context.

Corrective Action: Verify that the source and target are BLOB types.

-618 Description of Error: Error on copying blob data.

Corrective Action: Verify that you are using valid blobspaces.

-620 Description of Error: Unable to update next extent size.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-621 Description of Error: Unable to update new lock level.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please record the actions that precededthis error and notify the Informix Technical Support Department.

-622 Description of Error: Error on locating UNIQUE index index-name.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

Error Messages 45

Page 860: Manual Informix

-623 Description of Error: Unable to find UNIQUE CONSTRAINT constraint-name.

Corrective Action: Check that the name of CONSTRAINT you are trying todrop exists and is spelled correctly. You can obtain this information from thesysconstraints table.

-624 Description of Error: Unable to drop UNIQUE CONSTRAINT constraint-name.

Corrective Action: This is an internal error. Read the ISAM error for moreinformation. After verifying that the error has not been generated as theresult of a system limit or problem, please notify the Informix TechnicalSupport Department.

-625 Description of Error: UNIQUE name constraint-name already exists.

Corrective Action: Specify a name that has not been used for a prior UNIQUECONSTRAINT on this table. You can check the sysconstraints table to see thenames of existing UNIQUE CONSTRAINTs.

-802 Description of Error: Cannot open file for run (operating system error).

Corrective Action: Check that the file exists. If it is not found in your currentdirectory you will need to include a full pathname. Check that you haveoperating system read permission to access the file. Contact your SystemAdministrator if you need help with this action.

-804 Description of Error: Comment has no end.

Corrective Action: Comments can be enclosed within a pair of { and } braces.Edit your statement to include a matching right brace } to the left brace { thatdenotes the start of your comment.

Note: Comments cannot be nested.

-809 Description of Error: SQL syntax error has occurred.

Corrective Action: Check that you have not misspelled an SQL statement,placed keywords out of sequence, or included a reserved word in your query.

-816 Description of Error: Cannot read file (check file permissions).

Corrective Action: Check that you have operating system read permissionto access the file. Contact your System Administrator if you need help withthis action.

-817 Description of Error: Cannot write file (check file permissions).

Corrective Action: Check that you have operating system write permissionin the designated directory. Contact your System Administrator if you needhelp with this action.

46 Error Messages

Page 861: Manual Informix

-824 Description of Error: Missing values clause on insert statement.

Corrective Action: The INSERT INTO statement requires a VALUES clause.Check that you have included a VALUES clause (with a values list) in yourstatement.

-825 Description of Error: Program not found.

Corrective Action: INFORMIX-4GL could not locate a necessary program.Check that your INFORMIXDIR environment variable is properly set. Contactyour System Administrator if you need help with this action.

-826 Description of Error: Fork system call failed.

System Action: The statement did not run (operating system error).

Corrective Action: INFORMIX-4GL was unable to fork a necessary process.Pause a moment and reenter your request. If you receive this error messageagain, contact your System Administrator.

-827 Description of Error: Database not found.

Corrective Action: Check the spelling of the database name. Check that thedatabase name exists in your current directory or a directory specified inyour DBPATH environment variable.

-829 Description of Error: Form not found.

Corrective Action: Check the spelling of the form name. Make sure the theform exists in your current directory or a directory specified in your DBPATHenvironment variable.

-832 Description of Error: Error(s) found in form specifications.

Corrective Action: Edit the form specification file following the promptsprovided by FORM4GL. Recompile the form specification.

-834 Description of Error: form4gl could not compile the form.

Corrective Action: Attempt a second compile of the form, or run FORM4GLoutside of INFORMIX-4GL.

-836 Description of Error: Insert statement has no values clause.

Corrective Action: The INSERT INTO statement requires a VALUES clause.Check that you have included a VALUES clause (with a values list) in yourstatement.

Error Messages 47

Page 862: Manual Informix

-837 Description of Error: There is not enough memory available.

Corrective Action: There is insufficient data space in memory to run yourrequest. Save your program, exit from INFORMIX-4GL, and then reenterINFORMIX-4GL and run your program again. If this does not work, you mayneed to reduce the complexity of your program.

-839 Description of Error: Table not found.

Corrective Action: Check the spelling of the table name. Make sure thetable-name.dat, table-name.idx, and table-name.lok files are located in thedatabase-name.dbs directory.

-840 Description of Error: Name is too long.

Corrective Action: Database names must be ten characters or less. Select anew name of the appropriate length.

-841 Description of Error: Name must start with a letter and contain letters,digits, or underscores.

Corrective Action: Select a name beginning with a letter and containing onlyletters, digits, and underscores.

-842 Description of Error: Cannot read temp file.

Corrective Action: Check that you have operating system read permissionto access the file. Contact your System Administrator if you need help withthis action.

-843 Description of Error: Cannot write temp file.

Corrective Action: Check that you have operating system write permissionto create a file in the current directory, the /tmp directory, or the directoryindicated in your DBTEMP environment variable. Contact your SystemAdministrator if you need help with this action.

-844 Description of Error: Statement is too long (maximum 2,048 characters).

Corrective Action: Reduce the length of the statement to less than 2,048characters.

-846 Description of Error: Number of values in load file is not equal to thenumber of columns.

Corrective Action: Check that the number of values in the load file equalsthe number of columns in the table.

48 Error Messages

Page 863: Manual Informix

-847 Description of Error: Error in load file line line-no.

Corrective Action: See the accompanying error message for informationabout the source of the problem. Check the load file.

-851 Description of Error: Cannot drop file (check file permissions.)

Corrective Action: Check the access permissions on the file that you aretrying to drop.

-852 Description of Error: Write failed. integer rows unloaded (check ulimit ordisk space).

Corrective Action: Check with your system administrator to verify that youhave not run out of disk space.

-853 Description of Error: Current transaction has been rolled back.

Corrective Action: The transaction was rolled back as a result of a syntaxerror in your SQL statement or .sql file. Check the syntax of your SQL state-ments and retry the statement.

-900 Description of Error: Cannot read network user authorization file.

Corrective Action: Check that the network user authorization file exists onthe server, that it is accessible through the network, and that you have readpermission.

-901 Description of Error: User not found in network user authorization file.

Corrective Action: Add the user to the network authorization file.

-902 Description of Error: User not authorized or too many entries inauthorization file.

Corrective Action: Requires a version configured for more users. ContactInformix Software for assistance.

-904 Description of Error: Authorization file not on licensed INFORMIX-SQLserver.

Corrective Action: Reset the INFORMIXDIR variable to the directory thatcontains the licensed software.

-907 Description of Error: Cannot create socket on local system.

Corrective Action: Check that TCP/IP is installed and functioning properlythroughout the network.

Error Messages 49

Page 864: Manual Informix

-908 Description of Error: Attempt to connect to remote system failed.

Corrective Action: Verify that the remote system is up and functioning prop-erly. Check that the sqlexecd process on the remote system is running as abackground process and was started by root.

-909 Description of Error: Invalid database name format.

Corrective Action: Check that you have provided the remote database namein one of the forms explained in the INFORMIX-OnLine Programmer’s Manual.

-910 Description of Error: Cannot create an INFORMIX-OnLine database from anINFORMIX-SE client.

Corrective Action: Use an INFORMIX-OnLine client to create the database.

-911 Description of Error: System error - Cannot read from pipe.

Corrective Action: Reenter your request. If the problem persists, refer toyour system manual for more information about the source of the problem.

-912 Description of Error: Network error - Could not write to remote system.

Corrective Action: Reenter your request. If the problem persists, run yournetwork diagnostics to determine the source of the problem.

-913 Description of Error: Network error - Could not read from remote system.

Corrective Action: Reenter your request. If the problem persists, run yournetwork diagnostics to determine the source of the problem.

-914 Description of Error: System error - Cannot write to pipe.

Corrective Action: Reenter your request. If the problem persists, refer toyour system manual for more information about the source of the problem.

-915 Description of Error: Cannot create an INFORMIX-SE database from anINFORMIX-OnLine client.

Corrective Action: Use an INFORMIX-SE client to create the database.

-916 Description of Error: Cannot open /etc/mtab.

Corrective Action: Make sure that /etc/mtab is readable by the user.

-917 Description of Error: Must close current database before using a newdatabase.

Corrective Action: Close the current database and reenter your request for anew database.

50 Error Messages

Page 865: Manual Informix

-918 Description of Error: Unexpected data received from remote system.

Corrective Action: Reenter your request. If the problem persists, run yournetwork diagnostics to determine the source of the problem.

-919 Description of Error: System error. Wrong number of arguments to remotesqlexec process.

Corrective Action: Reenter your request. If the problem persists, refer toyour system manual for more information about the source of the problem.

-922 Description of Error: System error. Unable to fork remote sqlexec process.

Corrective Action: Check operating system permissions for the directory,and make sure that you have permission to access the directory.

-925 Description of Error: The protocol type should be tcp.

Corrective Action: Change the protocol type to tcp in$INFORMIXDIR/etc/sqlhosts.

-926 Description of Error: INFORMIX-OnLine is not licensed for distributed dataaccess.

Corrective Action: You cannot access tables or databases on remote systemsunless you have INFORMIX-STAR.

-927 Description of Error: Exceeded limit of maximum number of sites you canreference.

Corrective Action: The maximum number of sites that you can referenceis 32.

-928 Description of Error: The remote server is not licensed for distributed dataaccess.

Corrective Action: You have tried to access a table on an INFORMIX-OnLinesystem that is not licensed for remote access. You can only access otherINFORMIX-STAR systems.

-930 Description of Error: Cannot connect to remote host sitename.

Corrective Action: Check that the sitename that you are using is correct.Verify that the sitename has an entry in the required networking files.

-931 Description of Error: Cannot locate service-name service/tcp service in/etc/services.

Corrective Action: Check the /etc/services file on the client for the requiredentries.

Error Messages 51

Page 866: Manual Informix

-932 Description of Error: Error on network connection, system-call system callfailed.

Corrective Action: Check that your network hardware and software areinstalled and functioning properly throughout the network.

-933 Description of Error: Unknown network type specified in DBNETTYPE.

Corrective Action: Set your environment variable DBNETTYPE to starlan,tcp/ip, or some other supported network.

-951 Description of Error: User is not known on remote host.

Corrective Action: Verify that the user has a login on the host, and that thenetwork software is configured properly to accept this user name. Consultyour machine and network user manuals for assistance.

-952 Description of Error: User’s password is not correct for the remote host.

Corrective Action: Check your /etc/hosts.equiv file to be sure that both thehost machine you are attempting to connect to and the client machine you arecurrently logged into have entries in the file. If not, add the missing entry andreenter your request.

-953 Description of Error: Remote host could not execute sqlexec program.

Corrective Action: Verify that the INFORMIXDIR environment variable wasset on the server when the sqlexecd network server process was started byroot. If not, do this now and restart the sqlexecd process in the background.

-954 Description of Error: Client is not known to remote host.

Corrective Action: Verify that the host is aware of the client machine on thenetwork. If you are using TCP/IP, check your /etc/hosts file. Consult your net-work user manual for assistance.

-955 Description of Error: Remote host could not receive data from client.

Corrective Action: Verify that both the host machine and the client machineare configured properly, and that both machines are aware of each other onthe network. Consult your network user manual for assistance.

-956 Description of Error: Client is not in the file. /etc/hosts.equiv on the remotehost.

Corrective Action: Verify that the client machine name is in the/etc/hosts.equiv file on the remote host machine.

52 Error Messages

Page 867: Manual Informix

-999 Description of Error: Long transaction aborted.

Corrective Action: Your transaction has either filled up all of the availablelogical log space or it was waiting for a lock held by a transaction that filledall of the log space. If your transaction is long, decrease the length of theaborted transaction and retry. You can also increase the number of logicallogs on your system. If your transaction is not long, but it waits for locks, youcan retry the transaction and, depending on the timing, it might not conflictwith the long transaction again. Increasing the number of logical log files onyour system might also help, if your process is conflicting with other pro-cesses that have long transactions.

-1101 Description of Error: Variable address is NULL.

Corrective Action: After verifying that the error has not been generated asthe result of a system limit or problem, please notify the Informix TechnicalSupport Department.

-1102 Description of Error: Field name not found in form.

Corrective Action: A field name listed in an INPUT, INPUT ARRAY, DISPLAY,DISPLAY ARRAY, or CONSTRUCT statement does not appear in the form spec-ification file of the screen form that is currently displayed. Change the fieldname in the program or form specification file as appropriate and recompile.

-1107 Description of Error: Field subscript out of bounds.

Corrective Action: The subscript of a screen array in an INPUT, INPUTARRAY, DISPLAY, DISPLAY ARRAY, or CONSTRUCT statement is larger thanthe corresponding subscript in the SCREEN RECORD statement that definesthe screen array in the form specification file. Change the subscript in yourprogram or make the appropriate modifications to your form specificationfile.

-1108 Description of Error: Record not in form.

Corrective Action: The screen record in an INPUT, INPUT ARRAY, DISPLAY,DISPLAY ARRAY, or CONSTRUCT statement does not appear in the form spec-ification file. Change the screen record name in your program or in your formspecification file.

-1109 Description of Error: List and record field counts differ.

Corrective Action: The number of program variables or columns is not thesame as the number of fields in an INPUT, INPUT ARRAY, DISPLAY, DISPLAYARRAY, or CONSTRUCT statement. Check the variable-list or column-list andthe field-list to make sure they contain the same number of items.

Error Messages 53

Page 868: Manual Informix

-1110 Description of Error: Form file not found.

Corrective Action: The form file specified in the OPEN FORM statementcould not be found. Make sure that your program can access the form filespecified in the OPEN FORM statement.

-1111 Description of Error: Field table offset out of bounds.

Corrective Action: After verifying that the error has not been generated asthe result of a system limit or problem, please notify the Informix TechnicalSupport Department.

-1112 Description of Error: A form is incompatible with the current 4GL version.Rebuild your form.

Corrective Action: The form file specified in an OPEN FORM statement hasbeen corrupted, or was compiled with an older version of FORM4GL. Recom-pile the form specification file with the appropriate version of FORM4GL.

Note: Do not specify a file extension with the form name in an OPEN FORMstatement.

-1113 Description of Error: Memory allocation error.

Corrective Action: Divide your program into smaller programs.

-1114 Description of Error: No form has been displayed.

Corrective Action: Make sure you successfully execute an OPEN FORMstatement before a DISPLAY FORM statement.

-1115 Description of Error: Numeric value too long for field.

Corrective Action: Please check the entered value and make the necessarycorrection.

-1116 Description of Error: Default value from form field cannot be converted toinput variable type.

Corrective Action: The default value in a display field is not compatible withthe data type of the corresponding program variable in an INPUT or INPUTARRAY statement. Change the default value for the display field or changethe data type of the corresponding variable in the INPUT or INPUT ARRAYstatement.

-1117 Description of Error: Cannot convert date value to string.

Corrective Action: A DATE value in the database cannot be converted to astring. If the correct date is known, update the table to substitute a validDATE value.

54 Error Messages

Page 869: Manual Informix

-1119 Description of Error: NEXT FIELD name not found in form.

Corrective Action: The field name in the NEXT FIELD clause of an INPUT orINPUT ARRAY statement does not appear in the field-list of the statement.Change the NEXT FIELD clause or the field-list as appropriate.

-1120 Description of Error: Message file not found.

Corrective Action: The message file specified in the HELP FILE clause of theOPTIONS statement either could not be found or could not be read. Make sureyour program can access the message file specified in the OPTIONS HELP FILEstatement.

-1121 Description of Error: Message number not found in message file.

Corrective Action: A message number in an INPUT, PROMPT, or MENU state-ment does not appear in the corresponding message file. Change the messagenumber in your program or add a new message to the file and recompile.

-1122 Description of Error: Incompatible message file.

Corrective Action: The message file specified in the HELP FILE clause of theOPTIONS statement could not be read. Make sure the OPTIONS HELP FILEstatement specifies a compiled message file that is readable.

-1129 Description of Error: Field in BEFORE/AFTER clause not found in form.

Corrective Action: A field name in the BEFORE or AFTER clause of an INPUTor INPUT ARRAY statement does not appear in the form specification file ofthe screen form that is currently displayed. Change the field name in the pro-gram or form specification file as appropriate and recompile.

-1130 Description of Error: You cannot have multiple BEFORE clauses for the samefield.

Corrective Action: Combine the BEFORE clauses for the same field in INPUTor INPUT ARRAY statements.

-1131 Description of Error: You cannot have multiple AFTER clauses for the samefield.

Corrective Action: Combine the AFTER clauses for the same field in INPUTor INPUT ARRAY statements.

Error Messages 55

Page 870: Manual Informix

-1132 Description of Error: The destination string of the CONSTRUCT statement isnot large enough.

Corrective Action: The character variable for storing the user’s search crite-ria in a CONSTRUCT statement is not large enough to contain the constructedstring. Increase the size of the character variable in the appropriate DEFINEstatement and recompile your program.

-1133 Description of Error: The NEXT OPTION name is not in the menu.

Corrective Action: The NEXT OPTION name is not a menu option. Changethe menu option in the NEXT OPTION statement or the menu as appropriateand recompile your program.

-1134 Description of Error: There is no termcap entry for this function key.

Corrective Action: The specified key in the HELP KEY, INSERT KEY, DELETEKEY, NEXT KEY, or PREVIOUS KEY clause of an OPTIONS statement does notappear in the termcap or terminfo files. Add the code for the specified func-tion key to the termcap file, or add the code to your terminal file in the ter-minfo directory. See Appendix I of the INFORMIX-4GL Reference Manual fordetails.

-1135 Description of Error: The row or column number in DISPLAY AT exceeds thelimits of your terminal.

Corrective Action: Change the row or column number in the DISPLAY ATstatement so that it is within the limits of your screen or window.

-1136 Description of Error: Window is too large to fit on the screen.

Corrective Action: The window dimensions specified in the WITH clause ofthe OPEN WINDOW statement exceed the limits of your screen. Reduce thesize of the window dimensions, or change the originating location of the win-dow. If you are attempting to open the window WITH FORM, you mustreduce the size of the form. (When sizing a window to fit a form, INFOR-MIX-4GL truncates trailing blank spaces but prints leading blank spaces. Youmight remove any leading blank spaces.)

-1137 Description of Error: Cannot open window.

Corrective Action: Your INFORMIX-4GL program exceeds the data spacelimit of your system. Reduce the complexity of the program by closing one ormore windows or forms, or reducing the number of global variables.

56 Error Messages

Page 871: Manual Informix

-1138 Description of Error: Border does not fit on screen. Window is too large.

Corrective Action: The dimensions of the bordered window exceed the lim-its of your screen. Note that the border appears outside the dimensions of thewindow. Reduce the size of the window dimensions. If the termcap entry foryour terminal includes an sg#1 setting, or the terminfo entry includes anxmc#1 setting, INFORMIX-4GL reserves an additional column to the left andto the right of the window when computing the required window size.

-1139 Description of Error: Form line cannot be set using LAST keyword.

Corrective Action: You cannot use LAST or LAST-integer to set the Form line.You must indicate the Form line relative to FIRST or a literal value.

-1141 Description of Error: Cannot close window with active INPUT, DISPLAYARRAY, or MENU statement.

Corrective Action: You must complete the INPUT, DISPLAY ARRAY, orMENU statement before closing the current window.

-1142 Description of Error: Window is too small to display this form.

Corrective Action: The window dimensions specified in the WITH clause ofthe OPEN WINDOW statement are too small for the form. Either open the win-dow WITH FORM, or increase the dimensions in the WITH clause.

-1143 Description of Error: Window is already open.

Corrective Action: You cannot issue an OPEN WINDOW statement for a win-dow that is already open. Check your program logic to see whether youshould add a CLOSE WINDOW statement or delete an OPEN WINDOWstatement.

-1144 Description of Error: Cannot open window. Window origin is not on thescreen.

Corrective Action: The originating location specified in the AT clause of theOPEN WINDOW statement exceeds the limits of the screen. Specify a newlocation.

-1145 Description of Error: Cannot open ERROR window.

Corrective Action: Your INFORMIX-4GL program exceeds the data spacelimits of your system. Reduce the complexity of the program by closing oneor more windows or forms, or reducing the number of global variables.

Error Messages 57

Page 872: Manual Informix

-1146 Description of Error: PROMPT message is too long to fit in the window.

Corrective Action: Reduce the length of the PROMPT statement or enlargethe window. You will receive a run-time error if the window does not accom-modate the text of the PROMPT message along with the characters entered bythe user in response to the prompt.

Note: if necessary, INFORMIX-4GL truncates MESSAGE and COMMENT text.INFORMIX-4GL does not truncate the text of a PROMPT statement.)

-1147 Description of Error: You cannot CLOSE, CLEAR, or make CURRENT anunopened window.

Corrective Action: Check that you specified the correct window. You mustfirst execute an OPEN WINDOW statement before executing a CLOSEWINDOW, CLEAR WINDOW, or CURRENT WINDOW statement. In addition,you cannot execute these statements once the window is CLOSEd.

-1148 Description of Error: Size of a window may not be negative.

Corrective Action: Only positive integers or variables that evaluate to posi-tive integers can be used in the WITH clause of the OPEN WINDOW statement.

-1149 Description of Error: An unknown code has been detected in the form.

Corrective Action: Be sure that you have linked your 4GL program with thecorrect 4GL libraries. Relink your INFORMIX-4GL program with the mostrecent version of the INFORMIX-4GL libraries. Rebuild your form withFORM4GL.

-1150 Description of Error: Window is too small to display this menu.

Corrective Action: Increase the dimensions of the window to accommodatethe menu. At a minimum, the window must be two rows long and largeenough to display the menu title and a colon, the longest option, two sets ofellipses, and 6 spaces.

-1200 Description of Error: Number is too large for a DECIMAL data type.

Corrective Action: The range of numbers allowed as DECIMAL values hasbeen exceeded. Allowable decimal numbers range from 10-128 to 10126 inabsolute value (with 32 significant digits). Check the size of the number.

-1201 Description of Error: Number is too small for a DECIMAL data type.

Corrective Action: A number is outside the range of DECIMAL type values.Allowable decimal numbers range from 10-128 to 10126 in absolute value(with 32 significant digits). Check the size of the number.

58 Error Messages

Page 873: Manual Informix

-1202 Description of Error: An attempt was made to divide by zero.

Corrective Action: Check that you are not attempting to divide a numberdata type by a character data type (for example, 16/Jones ) or that the valueof the divisor does not equal zero.

-1203 Description of Error: Values used in a MATCH must both be typeCHARACTER.

Corrective Action: Check that the values included in your MATCH conditionare CHAR or VARCHAR types. Use an alternate comparison condition fornon-character data types.

-1204 Description of Error: Invalid year in date.

Corrective Action: Acceptable years are 0001 to 9999. If two digits are used,INFORMIX-4GL assumes the year is 19xx. Check the value entered in theDATE field.

-1205 Description of Error: Invalid month in date.

Corrective Action: In SQL statements such as INSERT, a month can be repre-sented as the number of the month (1 through 12). In display fields, a monthcan be represented either as the number of the month (1 through 12) or as thefirst three letters of the name of the month. Check the value entered in theDATE column or field.

-1206 Description of Error: Invalid day in date.

Corrective Action: Acceptable days are 01 through 31, unless the month hasfewer days. Check the value entered in the DATE column or field.

-1208 Description of Error: There is no conversion from non-character values tocharacter values.

Corrective Action: Number values cannot be converted to character valuesin SQL statements such as INSERT and UPDATE. Make sure that your SQLstatements do not attempt this kind of conversion.

-1209 Description of Error: Without any delimiters, this date must contain exactly6 or 8 digits.

Corrective Action: You must enter either 6 or 8 digits when specifying a datavalue to represent a DATE.

Error Messages 59

Page 874: Manual Informix

-1210 Description of Error: Date could not be converted to month/day/yearformat.

Corrective Action: Dates must be presented as month, day, and year (soAugust 4, 1989 is allowed, but 4 August, 1989 is not). Check the sequence ofcharacters entered in the DATE field.

-1211 Description of Error: Out of memory.

Corrective Action: You have exceeded the data space capacity on yourmachine. Reduce the complexity of your form.

-1212 Description of Error: Date conversion format string must contain a month,day, and year component.

Corrective Action: The FORMAT string used to format a DATE field mustcontain month, day, and year components. One of these is missing.

-1213 Description of Error: Character to numeric conversion error.

Corrective Action: Check that the values in the character string contain onlyASCII characters representing number data types. (A table of ASCII codes isincluded as Appendix H to this manual.)

-1214 Description of Error: Value too large to fit in a SMALLINT.

Corrective Action: Acceptable SMALLINT values are whole numbersbetween -32,767 and 32,767. If a larger number is required, use the ALTERTABLE statement to modify the column to INTEGER type.

-1215 Description of Error: Value too large to fit in an INTEGER.

Corrective Action: Acceptable INTEGER values are whole numbers between-2,147,483,647 and 2,147,483,647. If a larger number is required, use theALTER TABLE statement to modify the column to DECIMAL type.

-1216 Description of Error: Illegal exponent.

Corrective Action: Check that the exponent is an integer with a value notexceeding 32,767.

-1217 Description of Error: The format string is too large.

Corrective Action: Reduce the size of the FORMAT string (used to format aDATE field) in the form specification.

-1218 Description of Error: String to date conversion error.

Corrective Action: Check the format for the DATE data type in the DBDATEenvironment variable. The format is illegal.

60 Error Messages

Page 875: Manual Informix

-1222 Description of Error: Value will not fit in a SMALLFLOAT.

Corrective Action: Enter the appropriate value, depending on the machinethat you use.

-1223 Description of Error: Value will not fit in a FLOAT.

Corrective Action: Enter the appropriate value depending on the machineyou use.

-1224 Description of Error: Invalid decimal number.

Corrective Action: The value that you entered might be out of range. Referto the decimal value created at the time when you created the column.

-1225 Description of Error: Column does not admit a NULL value.

Corrective Action: This column does not accept NULL values. Make surethat the data value that you are attempting to insert is not NULL.

-1226 Description of Error: Decimal or money value exceeds maximum precision.

Corrective Action: Increase the precision of the DECIMAL or MONEY field.

-1227 Description of Error: Message file not found.

Corrective Action: Check to see if you have installed the product correctly.Alternately, you might be missing a message file. Search for the required mes-sage file.

-1228 Description of Error: Message number not found in message file.

Corrective Action: You might have a corrupted message file. Retrieve anuncorrupted message file by re-installing the product (or by re-editing andrecompiling 4glusr.msg, if you changed a message number in that file).

-1229 Description of Error: Incompatible message file.

Corrective Action: Retrieve uncorrupted version of message file by re-installing the product.

-1230 Description of Error: Bad message file name formulation.

Corrective Action: Check to see if you have entered the correct message filenames.

-1231 Description of Error: Cannot seek within message file.

Corrective Action: Re-install or rebuild your message files.

Error Messages 61

Page 876: Manual Informix

-1232 Description of Error: Message buffer too small.

Corrective Action: You may be out of memory. The internal buffer for Helpand other messages defaults to 128 bytes, but automatically resizes itself toaccommodate longer messages. This error usually means that your programis reading a very large file as a single message, or else that it is mistakenlyreading memory instead of a message file. Make sure that your message fileformat is correct, and then recompile it.

-1250 Description of Error: Unable to create pipes.

Corrective Action: Check the spelling of the name of the program receivingthe output. Check that the program is available on your system. Check thatthe program exists in a directory accessed in your PATH environment vari-able. Contact your System Administrator if you need help with these actions.

-1251 Description of Error: Unable to create shared memory. semget failed.

Corrective Action: This is an internal error. Follow the suggested actions forerror -1250. You may also be out of memory. After verifying that the error isnot the result of a system limit or problem, please notify the Informix Techni-cal Support Department.

-1252 Description of Error: Unable to create shared memory. shmget failed.

Corrective Action: This is an internal error. Follow the suggested actions forerror -1250. You may also be out of memory. After verifying that the error isnot the result of a system limit or problem, please notify the InformixTechnical Support Department.

-1254 Description of Error: Unable to connect to remote host.

Corrective Action: Follow the suggested actions for error -1250. Make surethat the network is operating properly, and check your spelling of the identi-fier of the remote system.

-1257 Description of Error: Operating system cannot fork process for back end.

Corrective Action: This is an internal error. Follow the suggested actions forerror -1250. After verifying that the error is not the result of a system limit orproblem, please notify the Informix Technical Support Department.

-1258 Description of Error: Cannot attach to shared memory used to communicatewith back end.

Corrective Action: This is an internal error. Follow the suggested actions forerror -1250. After verifying that the error is not the result of a system limit orproblem, please notify the Informix Technical Support Department.

62 Error Messages

Page 877: Manual Informix

-1260 Description of Error: It is not possible to convert between the specifiedtypes.

Corrective Action: A data type conversion must make sense; some, such asINTERVAL to DATE, or DATETIME to MONEY, are not supported. You mayhave referenced the wrong variable or column. Make sure that you havespecified the data types that you intended, and that any strings representingdata values are correctly formatted.

-1261 Description of Error: Too many digits in the first field of datetime orinterval.

Corrective Action: Specify fewer digits. The default precision is two (2)digits for every field, except year (4) and fraction (3). You can specify a non-default precision for fraction in the range 1 to 5. For the INTERVAL (but notDATETIME) data type, you can specify a non-default precision of up to 9digits for any field except fraction.

-1262 Description of Error: Non-numeric character in datetime or interval.

Corrective Action: You can only use digits and the required hyphen ( - ),blank ( ), colon ( : ), and period ( . ) separators in DATETIME and INTERVALconstants, or as the values within literals. See if you used the wrong separa-tor, included an extraneous blank, omitted a digit, omitted a separator, orentered the name of a month or day in place of digits.

-1263 Description of Error: A field in a datetime or interval is out of range.

Corrective Action: In an INTERVAL field, the absolute value of any field canrange from 0 to 10n -1, for n the declared precision. In a DATETIME value, theyear can range from 1 to 9999, the month from 1 to 12, and the day from 1 to amaximum from 28 to 31, depending on the specific month and year. The hourmust be a positive integer in the range 0 to 23. The minute and second must bepositive integers in the range 0 to 59. The fraction can range from 0 to 10n -1,for n the declared precision for the fraction field.

-1264 Description of Error: Extra characters at the end of a datetime or interval.

Corrective Action: See if you have included a blank within a field, enteredtoo many digits or too many fields, neglected the effect of an EXTEND func-tion, or made a typing mistake.

Error Messages 63

Page 878: Manual Informix

-1265 Description of Error: Overflow occurred on a datetime or intervaloperation.

Corrective Action: Both DATETIME and INTERVAL values are stored inter-nally as decimals. Your arithmetic operation produced a decimal overflow.Examine your program logic to see if you can change the sequence or preci-sion of your operations to avoid the overflow.

-1266 Description of Error: Intervals or Datetimes are incompatible for theoperation.

Corrective Action: The arithmetic operations permitted on INTERVAL andDATETIME (and DATE) values are listed in Appendix J. You may havereversed the order of operands, or attempted a meaningless operation, suchas adding two DATETIME values. Correct the logic of your program.

-1267 Description of Error: The result of a datetime computation is out of range.

Corrective Action: The range of allowed values for DATETIME andINTERVAL fields is described in the suggested actions for error -1263. Somefield in your result (probably the first) is too large, or is negative, or has aninvalid zero value. Check the terms in your calculation and your programlogic to see if you can change the sequence, scale, or precision of your opera-tion to avoid the out-of-range results.

-1268 Description of Error: Invalid datetime qualifier.

Corrective Action: Check spelling. You are restricted to the keywords YEAR,MONTH, DAY, HOUR, MINUTE, SECOND, and FRACTION. Do not append ‘‘S’’to a keyword.

-1269 Description of Error: Locator conversion error.

Corrective Action: This is an internal error. After verifying that the error isnot the result of a system limit or problem, please notify the Informix Techni-cal Support Department.

-1270 Description of Error: Interval literal may not have embedded minus sign.

Corrective Action: You can use a minus sign as an arithmetic or unaryoperator with INTERVAL literals, but not within any of its fields.

-1271 Description of Error: Missing decimal point datetime or interval.

Corrective Action: Use the decimal point ( . ) to separate the second and frac-tion fields, if both are present.

64 Error Messages

Page 879: Manual Informix

-1301 Description of Error: This value is not among the valid possibilities

Corrective Action: The system issues this warning during an INPUT orINPUT ARRAY statement when the user tries to enter data outside therange(s) specified for the field via the INCLUDE attribute in the form specifi-cation. Be sure to enter a value that appears in the INCLUDE list in the formspecification file.

-1302 Description of Error: The two entries were not the same—please try again.

Corrective Action: The system issues this warning during an INPUT orINPUT ARRAY statement when the user does not enter the same value twicein a display field that has been assigned the VERIFY attribute. The user mustenter the same value twice before the value will be accepted.

-1303 Description of Error: You cannot use this editing feature because a pictureexists.

Corrective Action: The system issues this warning during an INPUT orINPUT ARRAY statement when the user tries to use CTRL-A, CTRL-D, orCTRL-X in a display field that has been assigned the PICTURE attribute. Theuser should not use the CTRL-A, CTRL-D, or CTRL-X keys when entering datain a field that has been assigned the PICTURE attribute.

-1304 Description of Error: Error in field.

Corrective Action: The system issues this warning when the user tries toenter a value in a display field that cannot be converted to the data type ofthe corresponding program variable in the INPUT or INPUT ARRAY state-ment. The user must enter a value in a display field that is compatible withthe data type of the corresponding program variable in the INPUT or INPUTARRAY statement.

-1305 Description of Error: This field requires an entered value.

Corrective Action: The system issues this warning during an INPUT orINPUT ARRAY statement when the user tries to end input without entering avalue in a display field that has been assigned the REQUIRED attribute. Theuser must enter a value in the required field.

-1306 Description of Error: Please type again for verification.

Corrective Action: The system issues this message during an INPUT orINPUT ARRAY statement after the user enters a value once in a display fieldthat has been assigned the VERIFY attribute. The user should enter the samevalue again.

Error Messages 65

Page 880: Manual Informix

-1307 Description of Error: Cannot insert another row—the input array is full.

Corrective Action: The system issues this warning during an INPUT ARRAYstatement when the user tries to insert a row after the program array is full.The user should select another editing function or end input. If the userreceives this warning frequently, the user should have the applicationsdesigner increase the size of the program array.

-1308 Description of Error: Cannot delete row—it has no data.

Corrective Action: The system issues this warning during an INPUT ARRAYstatement when the user selects the delete function while the cursor is on theblank row below the last row of the program array. The user should selectanother editing function or end input.

-1309 Description of Error: There are no more rows in the direction you are going.

Corrective Action: The system issues this warning during an INPUT ARRAYor DISPLAY ARRAY statement when the user presses the [ ↑ ] or Previous Pagekey while the cursor is at the beginning of the program array or when theuser presses the [ ↓ ] or Next Page key while the cursor is at the end of theprogram array. The user should select another scrolling or editing function.

-1312 Description of Error: FORMS statement error number integer.

Corrective Action: Something is wrong with the input, display, or data typeconversion that your program specifies. Refer to the corresponding errornumber in this manual. (This error can occur with statements that do not usescreen forms.)

-1313 Description of Error: SQL statement error number integer.

Corrective Action: Refer to the corresponding error number in this manual.

-1314 Description of Error: Program stopped at module, line number integer.

Corrective Action: Look for additional messages to see why executionstopped.

-1315 Description of Error: 4GL run-time error number integer.

Corrective Action: Refer to the corresponding error number in this manual.

-1316 Description of Error: ISAM error number integer.

Corrective Action: Refer to the corresponding error number in this manual.

66 Error Messages

Page 881: Manual Informix

-1317 Description of Error: A numeric conversion error has occurred due toincompatibility between a calling program and its function parameters orbetween a variable and its assigned expression.

Corrective Action: Make sure that the data types of variables or functionparameters are compatible with the types of values assigned to them.

-1318 Description of Error: A parameter count mismatch has occurred betweenthe calling function and the called function.

Corrective Action: Make sure that the number of parameters in the callingstatement is the same as the number of parameters in the called function.

-1319 Description of Error: The 4GL program has run out of runtime data spacememory.

System Action: The program stops and running transactions are rolled back.

Corrective Action: Divide your program into smaller modules. Reduce thesize of arrays and character variables. Make sure that no function returns acharacter string longer than 512 characters.

-1320 Description of Error: A function has not returned the correct number ofvalues expected by the calling function.

Corrective Action: Make sure that the number of parameters after theRETURN keyword in the called function is the same as the number of param-eters after the RETURNING keyword in the calling statement.

-1321 Description of Error: A validation error has occurred as a result of theVALIDATE command.

Corrective Action: Make sure that the values of the variables in a VALIDATEstatement conform to the values allowed for the corresponding columns inthe syscolval table.

-1322 Description of Error: A report output file cannot be opened.

Corrective Action: Check that you have operating system write permissionin the designated directory. Contact your System Administrator if you needhelp with this action.

-1323 Description of Error: A report output pipe cannot be opened.

Corrective Action: Check the spelling of the name of the program receivingthe output. Check that the program is available on your system. Check thatthe program exists in a directory accessed in your PATH environment vari-able. Contact your System Administrator if you need help with these actions.

Error Messages 67

Page 882: Manual Informix

-1324 Description of Error: A report output file cannot be written to.

Corrective Action: Check that you have WRITE access to the file in the des-ignated directory. Contact your System Administrator if you need help withthis action.

-1325 Description of Error: PRINT FILE error—cannot open file filename forreading.

Corrective Action: Check that the specified file exists, and that you haveREAD access to it. Contact your System Administrator if you need help withthis action.

-1326 Description of Error: An array variable has been referenced outside of itsspecified dimensions.

Corrective Action: Check that the number of subscripts for the array corre-sponds to the number of dimensions specified in the array definition. Checkthat the subscript(s) do not exceed the value(s) specified in the array defini-tion. Compile with the -a option to check array dimensions.

-1327 Description of Error: An insert statement could not be prepared for insert-ing rows into a temporary table used for a report.

Corrective Action: Check to see that you have CONNECT permission to thedatabase used by the program. Set all system access permissions to allow youto write into the database directory.

-1328 Description of Error: A temporary table needed for a report could not becreated in the selected database. The user must have permission to createtables in the selected database.

Corrective Action: Check that the user has CONNECT privilege for theselected database. Check the error number that appears with this error formore information about the source of the problem.

-1329 Description of Error: A database index could not be created for a temporarydatabase table needed for a report.

Corrective Action: Check the error number that appears with this error formore information about the source of the problem.

-1330 Description of Error: A row could not be inserted into a temporary reporttable.

Corrective Action: Check the error number that appears with this error formore information about the source of the problem.

68 Error Messages

Page 883: Manual Informix

-1331 Description of Error: A row could not be fetched from a temporary reporttable.

Corrective Action: Check the error number that appears with this error formore information about the source of the problem.

-1332 Description of Error: A character variable has referenced subscripts that areout of range.

Corrective Action: Make sure that a subscript for a character variable doesnot exceed the number of characters specified in the variable definition.

-1333 Description of Error: Strings of length > 512 cannot be returned fromfunction calls.

Corrective Action: Make sure that a character string returned by a functiondoes not exceed 512 characters.

-1334 Description of Error: The 4GL program cannot allocate any more space fortemporary string storage.

Corrective Action: INFORMIX-4GL cannot allocate more than 512 charactersfor temporary string storage. This error can occur if the nested functions in aCALL statement return strings whose total length exceeds 512 characters.

-1335 Description of Error: A report is accepting output or being finished before ithas been started.

Corrective Action: Be sure that the program runs START REPORT before itattempts to run OUTPUT TO REPORT or FINISH REPORT.

-1336 Description of Error: Module module-name in the pcode file contains pcodeversion num1. This program can run pcode version num2. Run the pcodecompiler with ‘‘-V’’ to check the pcode version that it produces, and thenrecompile all modules of your program and run it again.

Corrective Action: Check the p-code version, recompile, and run themodules.

-1337 Description of Error: The variable variable-name has been redefined with adifferent type or length.

Corrective Action: The lengths and types of global variables in two modulesmust be consistent. Make the definitions consistent and recompile theprogram.

Error Messages 69

Page 884: Manual Informix

-1338 Description of Error: The function function-name has not been defined in anymodule in the program.

Corrective Action: This suggests that the function function-name has beencalled, but is not in any module in the program. Supply the function in oneof the modules and recompile.

-1339 Description of Error: Global variable variable-name cannot be found in thedescriptor table.

Corrective Action: Please call your Informix representative.

-1340 Description of Error: The error log has not been started.

System Action: The ERRORLOG (‘‘message’’) library function does notappend a message to the error log.

Corrective Action: Be sure to include a CALL STARTLOG (‘‘full-pathname’’)statement if you want to maintain an error log.

-1343 Description of Error: No help file specified.

Corrective Action: The user pressed the Help key before an OPTIONS HELPFILE statement was executed. Make sure to execute the appropriate OPTIONSHELP FILE statement before allowing the user to request help during anINPUT, PROMPT, or MENU statement.

-1345 Description of Error: Undefined opcode.

Corrective Action: A function cannot be executed because your p-code filehas become corrupted. Recompile your source code.

-1346 Description of Error: Number is too large for a DECIMAL data type.

Corrective Action: The range of values allowed as a DECIMAL data type hasbeen exceeded. Allowable decimal numbers range from 10-128 to 10126 inabsolute value (with 32 significant digits). Check the size of the number.

-1347 Description of Error: Number is too small for a DECIMAL data type

Corrective Action: The range of values allowed as a DECIMAL data type hasbeen exceeded. Allowable decimal numbers range from 10-128 to 10126 inabsolute value (with 32 significant digits). Check the size of the number.

-1348 Description of Error: An attempt was made to divide by zero.

Corrective Action: Check that you are not attempting to divide a numbercolumn type by a character column type (for example, 1990/Three ) or thatthe value of the divisor does not equal zero.

70 Error Messages

Page 885: Manual Informix

-1349 Description of Error: Character to numeric conversion error.

Corrective Action: Check that the values in the character string contain onlyASCII characters representing number data types. (A table of ASCII codes isincluded as Appendix H to this manual.)

-1350 Description of Error: It is not possible to convert between the specifiedtypes.

Corrective Action: Examine your code to make sure that you have specifiedthe data types that you intended, and that any date or time expressions arecorrectly formatted. Some conversions (such as INTERVAL to MONEY) are notsupported, because the meaning of the conversion is obscure.

-1353 Description of Error: Use ’!’ to edit TEXT and BYTE fields.

Corrective Action: The INFORMIX-4GL editors cannot modify TEXT andBYTE fields. BLOB values can be modified only by outside programs, such asspreadsheets, word-processors, and so forth. Use the PROGRAM attribute inthe form specification file to specify the outside program for this field. Pressthe exclamation point ( ! ) key to invoke the outside program.

-1355 Description of Error: Cannot build temporary file.

Corrective Action: There is insufficient disk space to build a temporary copyof the TEXT or BYTE variable.

-1356 Description of Error: Write error on temporary file filename.

Corrective Action: An I/O error occurred while trying to write the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

-1357 Description of Error: Read error on temporary file filename.

Corrective Action: An I/O error occurred while trying to read the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

-1358 Description of Error: Write error on blob file filename.

Corrective Action: An I/O error occurred while trying to write the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

-1359 Description of Error: Read error on blob file filename

Corrective Action: An I/O error occurred while trying to read the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

Error Messages 71

Page 886: Manual Informix

-1360 Description of Error: No "PROGRAM=" clause for this field.

Corrective Action: This key ( ! ) invokes an editing program that can bespecified by the PROGRAM attribute. If you want to access that editor, youmust first assign the PROGRAM attribute to this field in the ATTRIBUTES sec-tion of the form specification file, and then use FORM4GL to recompile thescreen form.

-1361 Description of Error: Illegal blob file name. Null names are not permitted.

Corrective Action: You must specify a valid name for the file that containsthis binary large object (BLOB) of data type TEXT or BYTE.

-2013 Description of Error: The output form file filename cannot be opened.

Corrective Action: Check that you have operating system write permissionin the designated directory. Contact your System Administrator if you needhelp with this action.

-2014 Description of Error: There was an incorrect number of arguments on theoperating system command line. At least one argument is expected.

Corrective Action: FORM4GL requires that you include a filename on thecommand line (unless you use the -d option to FORM4GL). Carefully reenterthe command, including the filename as an argument, or use the -d option toFORM4GL. The correct syntax is as follows: form4gl form-name

-2015 Description of Error: An open comment symbol, {, was found inside analready open comment on line lineno, character charposition. This could bedue to a failure to close the previously opened comment, which was begunon line lineno, character charposition.

Corrective Action: Comments must be enclosed within a pair of braces({ and }). Insert a close comment symbol where appropriate. (Note: com-ments cannot be nested.) Recompile the form specification.

-2016 Description of Error: A comment has been opened, but not closed. The lastcomment begun was opened on line lineno, character charposition.

Corrective Action: Comments must be enclosed within a pair of braces({ and }). Insert a close comment symbol where appropriate. Recompile theform specification.

-2017 Description of Error: The character data value does not convert correctly tothe field type.

Corrective Action: Check that the values in the character string contain onlyASCII characters, and represent a value of the appropriate data type. See if adate or time separator is incorrect.

72 Error Messages

Page 887: Manual Informix

-2018 Description of Error: A grammatical error has been found on line lineno,character charposition. The construct is not understandable in its context.

Corrective Action: Check the grammatical content of the statement (place-ment of commas, braces, and so on). Recompile the form specification.

-2019 Description of Error: This integer exceeds the maximum size allowed.

Corrective Action: Allowable INTEGER values are whole numbers thatrange from -2,147,483,647 to 2,147,483,647. Check the value of the number(number of digits and location of the decimal point). If a larger number isrequired, you will need to use the ALTER TABLE statement to modify the col-umn to DECIMAL type. Recompile the form specification.

-2020 Description of Error: The table table-name could not be opened. The operat-ing system was asked to open it for writing.

Corrective Action: Check that you have operating system write permissionto create a file in the designated directory. Contact your System Administra-tor if you need help with this action. Recompile the form specification.

-2021 Description of Error: An illegal color has been specified. Colors 0 through 7are white, yellow, magenta, red, cyan, green, blue, and black.

Corrective Action: See if you misspelled a color name listed in the message.The form specification cannot reference colors by number, nor by names fromthe colornames file.

-2022 Description of Error: This identifier exceeds the maximum length for iden-tifiers, which is 50.

Corrective Action: Check that all field names, field labels, and identifiers areless than or equal to 50 characters in length. Recompile the form specification.

-2023 Description of Error: This quoted string exceeds the maximum length forquoted strings, which is 80.

Corrective Action: Reduce the number of characters in the quoted string to80 or less. Recompile the form specification.

-2024 Description of Error: There is already a record record-name specified. If therecord-name is the same as a table-name in the form, a default record of thesame name is created.

Corrective Action: You have already defined a record or a table with thesame name. Names of records must be unique.

Error Messages 73

Page 888: Manual Informix

-2025 Description of Error: The comment close symbol ( } ) has been found on linelineno, character charposition, even though no comment has been opened.

Corrective Action: Comments must be enclosed within a pair of braces({ and }). Remove the close comment symbol if it is unnecessary or insert anopen comment symbol where appropriate. Recompile the form specification.

-2026 Description of Error: The FORMONLY field field-name does not have a typespecified. A type must be specified if include lists or default values arespecified.

Corrective Action: Include a type specification after the field-name.

-2027 Description of Error: An illegal (invisible, control) character has been foundon line lineno, character charposition. It has been replaced by a blank in the list-ing, but it is still in the source (input) table, and should be removed beforeattempting to compile again.

Corrective Action: Remove the illegal character from the form specificationfile before attempting the next compile. You can use the following command:

od -c form-name

This command generates octal code that can help isolate the error. See theUNIX Programmer’s Manual for more information.

-2028 Description of Error: The symbol symbol-name does not represent a tableprefix used in this form. It cannot be used here to select record elements.

Corrective Action: Check to make sure that the table prefixes of all recordelements are actual tables in the form.

-2029 Description of Error: Screen record array arrayname has component sizesthat either differ from the specified dimension of the array or differ amongthemselves.

Corrective Action: The array size must match the number of components inthe screen section.

-2030 Description of Error: A typographical error has been found on line lineno,character charposition.

Corrective Action: Edit the form specification file where indicated and cor-rect the error. Recompile the form specification.

-2031 Description of Error: The WORDWRAP attribute can only be specified forCHAR, VARCHAR and TEXT fields.

Corrective Action: See if you have specified the wrong field tag or columnname, or the wrong data type of a FORMONLY field.

74 Error Messages

Page 889: Manual Informix

-2032 Description of Error: The number above could not be successfully con-verted to either an INTEGER or a DOUBLE or a LONG.

Corrective Action: FORM4GL could not convert the number provided.Acceptable LONG values are whole numbers between -2,147,483,647 and2,147,483,647. Check that the number does not exceed these values (if a fixedpoint number) or that it does not contain an error (if a decimal number).Recompile the form specification.

-2033 Description of Error: The field field-name has a default value not within therange of its include list values.

Corrective Action: If you have an include list and a default, the default mustbe within the include list range.

-2035 Description of Error: The WORDWRAP attribute, if specified, should applyto all the columns in a join.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2036 Description of Error: The display lines of a multi-line field lie in differentscreen pages.

Corrective Action: If the height of your page layout (plus the 4 reservedlines) is taller than the physical screen, or larger than the explicit or defaultvertical lines dimension in your SCREEN section or command line, FORM4GLdivides the form by beginning a new page after the last line that can fit on thefirst (and subsequent) pages. This happened within your WORDWRAP field.Correct your form, so that the height of the page layout is no greater than lines- 4. You may need another form to display other fields.

-2037 Description of Error: The PROGRAM attribute can only be specified for BYTEand TEXT fields.

Corrective Action: See if you have specified the wrong field tag or columnname, or the wrong data type of a FORMONLY field.

-2038 Description of Error: BLOB fields cannot be joined.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2039 Description of Error: The attributes AUTONEXT, DEFAULT, INCLUDE,VERIFY, RIGHT and ZEROFILL are not supported for BLOB fields.

Corrective Action: Ignore this message. It applies to features of PERFORMforms that 4GL does not support.

Error Messages 75

Page 890: Manual Informix

-2040 Description of Error: The formname form-name exceeds the maximumlength of 10 characters.

Corrective Action: Check the spelling of form-name. Recompile the formspecification.

-2041 Description of Error: The form form-name cannot be opened. This isprobably because it does not exist, or the user does not have read permission.

Corrective Action: Check the spelling of form-name. Recompile the formspecification.

-2042 Description of Error: The usage of a BLOB field in or around the above state-ment is incorrect.

Corrective Action: You have specified an attribute that does not supportTEXT or BYTE fields, or else your condition for the COLOR attribute cannot beapplied to a BLOB.

-2043 Description of Error: Screen layout exceeds the specified screen width. Thisis a warning only.

System Action: Your form successfully compiled.

Corrective Action: According to your explicit or default column specifica-tion, part of your screen layout lies beyond the right-hand limit of the formor of the physical screen. 4GL programs can use the form, but users may notbe able to see part of it. To avoid this effect, use a narrower page layout.

-2044 Description of Error: At most one color attribute may be specified for eachfield with each condition.

Corrective Action: Correct your ATTRIBUTE section, so that no conditionassigns multiple colors to the same field.

-2045 Description of Error: The conditional attributes of a 4GL field cannotdepend on the values of other fields.

Corrective Action: Correct your ATTRIBUTE section, so that no field tagexcept that of the current field appears in the condition.

-2100 Description of Error: Field field-tag has validation string error, String = char-acter-string

Corrective Action: Check that the values in the character string contain onlyASCII characters, and represent a value of the appropriate data type.

76 Error Messages

Page 891: Manual Informix

-2800 Description of Error: The first line of the specification must be the keywordDATABASE followed by the database name, or the FORMONLY keyword (4GLonly). An optional WITHOUT NULL INPUT may also follow.

Corrective Action: Check the spelling of the first line of the form specifica-tion file, or check that the keyword DATABASE is followed by the databasename or the FORMONLY keyword. Recompile the form specification.

-2810 Description of Error: The name database-name is not an existing databasename.

Corrective Action: Check the spelling of database-name. Check that data-base-name exists in your current directory or a directory included in yourDBPATH environment variable. Recompile the form specification.

-2811 Description of Error: The temporary table table-name could not be openedfor writing.

Corrective Action: Check that you have operating system write permissionto create the file. Contact your System Administrator if you need help withthis action. Recompile the form specification.

-2812 Description of Error: The temporary table table-name could not be read.

Corrective Action: Check that you have operating system read permissionto access the file. Contact your System Administrator if you need help withthis action. Recompile the form specification.

-2820 Description of Error: The label name between brackets is incorrectly givenor the label is missing.

Corrective Action: Check that the field tag ( = label name) exists and is cor-rectly spelled. Recompile the form specification.

-2830 Description of Error: A left square bracket has been found on this line, withno right bracket to match it.

Corrective Action: A set of brackets [ ] is used to delimit the field size of eachfield. Insert a right square bracket ( ] ) where appropriate into the form spec-ification file. Note that a display field cannot be split across lines. For a mul-tiple-line field to which you assign the WORDWRAP attribute, each segmentmust be indicated by delimiters, with the same field tag repeated in each seg-ment of the field. Recompile the form specification.

-2831 Description of Error: The control block has exceeded the maximum of 20fields.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

Error Messages 77

Page 892: Manual Informix

-2832 Description of Error: This form uses "|" to both start and end a field place-ment. Because of this, the form must specify left and right delimiters, whichare the same character. This is done with a DELIMITERS command in theINSTRUCTIONS section.

Corrective Action: The DELIMITERS section must specify the same 2characters for the left and right delimiters.

-2834 Description of Error: NULL cannot be used as the default. It is already thedefault if you specify nothing.

Corrective Action: Do not specify NULL for the DEFAULT attribute.

-2840 Description of Error: The label label-name was not defined in the form.

Corrective Action: Check that the field tag label-name is included in both theSCREEN and ATTRIBUTES sections of the form specification file, or delete theunnecessary label-name. (This error often accompanies errors -2820 and-2975.) Recompile the form specification.

-2841 Description of Error: The form must include a tables declaration before theattributes section.

Corrective Action: Include a TABLES section before the ATTRIBUTES section.

-2843 Description of Error: The column column-name does not appear in the formspecification.

Corrective Action: Be sure all fields in the ATTRIBUTES section appear in theSCREEN section.

-2844 Description of Error: The column column-name is associated with more thanone field in the form specification.

Corrective Action: You have specified a record element that appears in morethan one field. Check to see if you need to include a table name in the recordelement.

-2845 Description of Error: The composite column for table tab-name containingcolumn col-name is not indexed. Performance will be much improved by cre-ating an index on the column.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2846 Description of Error: The field field-name is not a member of the tabletable-name.

Corrective Action: Be sure the field is a column in the specified table.

78 Error Messages

Page 893: Manual Informix

-2850 Description of Error: The name column-name is not a column name in thisdatabase.

Corrective Action: Check the spelling of the column-name column name.Recompile the form specification.

-2856 Description of Error: The TODAY attribute can be assigned only to datecolumns.

Corrective Action: Check that the field in which the TODAY keyword hasbeen used is a DATE or DATETIME column. If appropriate, remove the TODAYkeyword from the ATTRIBUTES section of the form. Recompile the formspecification.

-2859 Description of Error: The column column-name is a member of more thanone table—you must specify the table name.

Corrective Action: The column name column-name appears in more than onetable used in the form. You must specify the table from which column-name isto be accessed, using the format table-name.column-name. Recompile the formspecification.

-2860 Description of Error: There is a column/value type mismatch for col-umn-name.

Corrective Action: Check that the value provided as the DEFAULT attributeor listed in the INCLUDE list matches the data type of the column (for exam-ple, DATE for a date column, or INTEGER for an integer). Recompile the formspecification.

-2861 Description of Error: You have exceeded the maximum of tables.

Corrective Action: A maximum of 20 (this number might be larger on somesystems) tables can be in use at any one time. Reduce the number of tablesincluded in the form. Recompile the form specification.

-2862 Description of Error: The table table-name cannot be found in the database.

Corrective Action: Check the spelling of table-name. Recompile the formspecification.

-2863 Description of Error: The column column-name does not exist among thespecified tables.

Corrective Action: Check the spelling of the column name or check thatcolumn-name does exist in one of the specified tables. Recompile the formspecification.

Error Messages 79

Page 894: Manual Informix

-2864 Description of Error: The table table-name is not among the specified tables.

Corrective Action: Check the spelling of table-name in the ATTRIBUTES sec-tion of the file. Check that the table is specified in the TABLES section of yourform. Recompile the form specification.

-2865 Description of Error: The column column-name does not exist in the tabletable-name.

Corrective Action: Check the spelling of column-name. Recompile the formspecification.

-2866 Description of Error: The NOW attribute may be assigned only to datetimecolumns.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2867 Description of Error: The CURRENT attribute may be assigned only todatetime columns.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2870 Description of Error: The subscripted column size does not match the spaceallocated in the display field.

Corrective Action: Check that the space provided in the display field isgreater than or equal to the subscripted column size. Recompile the formspecification.

-2880 Description of Error: The word 'screen' or 'end' has been left out.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2890 Description of Error: A screen definition must begin with a left curlybracket {.

Corrective Action: Each screen layout must be enclosed within a pair ofbraces { }. Edit your statement to include the necessary left brace. Note thatthe left brace must appear in the first character position on the line. Recom-pile the form specification.

80 Error Messages

Page 895: Manual Informix

-2892 Description of Error: The column column-name name appears more thanonce. If you wish a column to be duplicated in a form, use the same displayfield label.

Corrective Action: The column name column-name appears more than oncein the ATTRIBUTES section of the form specification file. Use the same fieldtag (in the SCREEN section) to denote the repeated column, and remove anyduplicate column names from the ATTRIBUTES section. If you want a multi-ple-line field to display long strings on several lines of the form, use the samefield tag in the SCREEN section for each segment of the field, and assign theWORDWRAP attribute to that field tag in a single line of the ATTRIBUTES sec-tion. Recompile the form specification.

-2893 Description of Error: The display field label field-tag appears more than oncein this form, but the lengths are different.

Corrective Action: A field tag ( = display field label) can appear more thanonce in the SCREEN section, but in every instance the display fields must haveidentical lengths. Edit the field delimiters so that they are of equal length.Recompile the form specification.

-2895 Description of Error: Display field length of number does not match thedatabase column length of number. This is a warning only.

Corrective Action: Check that the display field length (included in theSCREEN section) is equal to the table column size. (This error occurs only incharacter fields and with the -v option to FORM4GL.)

-2901 Description of Error: Field field-name contains two conflicting attributes,attribute1 and attribute2.

Corrective Action: The UPSHIFT and DOWNSHIFT attributes cannot both beassigned to the same field; nor can NOENTRY and REQUIRED be assignedtogether, nor NOENTRY and VERIFY.

-2920 Description of Error: The column col-name is a dominant column but it is notindexed. Performance will be much improved by creating an index on thecolumn.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2921 Description of Error: The database database-name is not compatible with thecurrent version of SQL.

Corrective Action: The database was created under a prior version ofINFORMIX. You must first convert the database, using sqlconv, beforeattempting to compile.

Error Messages 81

Page 896: Manual Informix

-2930 Description of Error: Portions of the column column-name are displayed onthe screen more than once.

Corrective Action: Check the subscripting of column-name (present in theATTRIBUTES section of the form specification file). Subscripts cannot overlap(for example, [25-49] and [50-75] are acceptable; [25-50] and [50-75] are unac-ceptable, as character 50 would have to appear twice). Recompile the formspecification.

-2931 Description of Error: There is an error in the format specification.

Corrective Action: You can only use the FORMAT attribute with a DECIMAL,SMALLFLOAT, FLOAT, or DATE value to control the format of the display.Check the format specifications for errors. Recompile the form specification.

-2932 Description of Error: Formats can be specified only for DECIMAL, SMALL-FLOAT, FLOAT or DATE columns.

Corrective Action: You can only use the FORMAT attribute with a DECIMAL,SMALLFLOAT, FLOAT, or DATE column to control the format of the display.Check that you have not specified the format on a CHAR, DATETIME,INTEGER, INTERVAL, or SMALLINT data type. Recompile the formspecification.

-2933 Description of Error: The format width is larger than the allocated displaywidth.

Corrective Action: Check that the format of a DECIMAL, SMALLFLOAT,FLOAT, or DATE column matches the length of the display field in the form.Recompile the form specification.

-2934 Description of Error: The format width is less than the allocated displaywidth. This is a warning only.

System Action: The compile was completed.

Corrective Action: Check that the format of a DECIMAL, SMALLFLOAT,FLOAT, or DATE column matches the length of the display field in the form.

Note: Until this error is corrected, any data displayed in the field mightbe truncated.)

-2935 Description of Error: The number of lines specified with the '-l' option or inthe screen section must be a positive integer from 6 to 600.

Corrective Action: Your vertical dimension is out of range. Specify a positivevalue between 6 and (lines - 4), for the number of rows that your physicalscreen can display.

82 Error Messages

Page 897: Manual Informix

-2936 Description of Error: The number of columns specified with the '-c' optionor in the screen section must be a positive integer from 30 to 600.

Corrective Action: Your horizontal dimension is out of range. Specify a pos-itive value between 30 and the width (in characters) of your physical screen.

-2940 Description of Error: The column column-name appears both with and with-out subscripts.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2943 Description of Error: You have exceeded the pseudo machine capacity.

Corrective Action: Reduce the complexity and/or number of the instruc-tions in the form. Recompile the form specification.

-2944 Description of Error: You may apply the AFTER ADD, UPDATE, QUERY, orREMOVE commands to a table only—not a column.

Corrective Action: Ignore this message. It applies to features of PERFORMforms that 4GL does not support.

-2945 Description of Error: You may not calculate an aggregate on the displayfield field-name because none of its associated database columns belong to thetable table-name.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2946 Description of Error: You may not calculate an aggregate on the display-only field field-name.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2950 Description of Error: The column column-name has no section that starts at1. Remember that the first subscript is one, not zero.

Corrective Action: Edit the form specification file so that the subscript to thecolumn column-name begins with 1 (and not 0). Recompile the formspecification.

-2951 Description of Error: The left and right delimiters must be specified in atwo-character string.

Corrective Action: When changing the delimiters that INFORMIX-4GL usesto enclose the display fields in the SCREEN section of a form, you must specifyboth the left and right delimiters with one character each. Recompile the formspecification.

Error Messages 83

Page 898: Manual Informix

-2952 Description of Error: In order to use a picture, the picture length must be thesame as the display field length.

Corrective Action: Edit the file so that the length of the picture specifiedwith the PICTURE attribute equals the display field length in the SCREEN sec-tion. Recompile the form specification.

-2955 Description of Error: The name field-tag is not a displayed field in this form.

Corrective Action: The display field field-tag has been specified in theATTRIBUTES section of the form specification file, but the field-tag is notincluded in the SCREEN section of the form. Delete the field-tag from theATTRIBUTES section or include it in the SCREEN section. Recompile the formspecification.

-2958 Description of Error: You may have a maximum of ten parameters in a C-function.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2959 Description of Error: Two tables may join with a maximum of integer col-umn pairs, including all components of composite columns.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2970 Description of Error: The column column-name joins with other columns, butit is not indexed. It is recommended that columns be indexed for cross-tablequeries. Performance will be much improved by creating an index on thecolumn.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2971 Description of Error: This column is not a character column, and thereforecannot be subscripted.

Corrective Action: Remove subscripting from any non-CHARACTERcolumns in your form. Recompile the form specification.

-2972 Description of Error: This column cannot be right justified or zero-filledbecause its displayed width does not match the actual column width.

Corrective Action: Make sure the field width in the SCREEN section matchesthe column length.

84 Error Messages

Page 899: Manual Informix

-2973 Description of Error: There may be only one dominant column in a displayfield description.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2975 Description of Error: The display field label field-tag has not been used.

Corrective Action: The field tag ( = display field label) field-tag present in theSCREEN section of the form specification file does not correspond to any fieldname in the ATTRIBUTES section. Delete field-tag from the SCREEN section ifit is unnecessary, or else reference it in the ATTRIBUTES section if you haveneglected to assign it a name. Recompile the form specification.

-2976 Description of Error: The end of the form has been reached prematurely.

Corrective Action: You have a SCREEN section with no following sections.Edit your form specification file to specify any necessary table names oraliases, field names, non-default screen arrays, or any other requiredinformation.

-2977 Description of Error: Table table1 cannot be a master of table table2 becausethey do not join.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2978 Description of Error: The column col-name1 and the column col-name2 can-not be joined columns because their types or lengths are different.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2984 Description of Error: The table identifier table-alias is defined more thanonce.

Corrective Action: Correct the TABLES section, so that each table alias isassociated with only one database table.

-2985 Description of Error: The table identifiers name and name represent the sametable.

Corrective Action: Correct the TABLES section, so that each table alias isassociated with a different database table.

-2986 Description of Error: The form specification has exceeded the maximum ofinteger master/detail pairs.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

Error Messages 85

Page 900: Manual Informix

-2987 Description of Error: The form specification has exceeded the maximumnumber of screens.

Corrective Action: If you specify more than one SCREEN section, each beginsa new page of the same form. Similarly, if the height of your page layout (plusthe 4 reserved lines) is taller than the physical screen, or larger than theexplicit or default vertical lines dimension in your SCREEN section or com-mand line, FORM4GL divides the form by beginning a new page after the lastline that can fit on the first (and subsequent) pages. Your form requires morethan 20 pages.

Redesign and recompile your form, so that the page layout fits on a singlepage. Use multiple forms or windows, rather than multiple pages, if youneed to display more fields.

-2988 Description of Error: FORM4GL has run out of memory.

Corrective Action: You have exceeded the data space limit on your machine.Reduce the complexity of the form specification file. Recompile the formspecification.

-2989 Description of Error: The column column-name is a reference column, but itis not indexed. It is recommended that reference columns be indexed forlookups. Performance will be much improved by creating an index on thecolumn.

Corrective Action: Ignore this message. It applies to features of PERFORMforms that 4GL does not support.

-2991 Description of Error: Warning: Only the first screen of your multiple-screenform will be displayed under 4GL.

System Action: The compilation was successful, but it produced a form withmore than one page.

Corrective Action: FORM4GL issues this warning because 4GL programscan access a multiple-page form, but cannot properly display any pageexcept the first. See if you have more than one SCREEN section, or if the pagelayout exceeds the height limit imposed by the explicit or default lines dimen-sion of your form or of the physical screen. You may have forgotten to allowfor the 4 lines required by the system, or reversed the vertical and horizontalspecifications. (See the description of -2987 for more information.)

To avoid concealing display fields, you must redesign and recompile yourscreen form so that it has only one page. Make the page layout no taller than(lines - 4). Use multiple forms or windows if you need to display more fieldsthan can fit on a single page.

86 Error Messages

Page 901: Manual Informix

-2992 Description of Error: The display label field-tag has already been used.

Corrective Action: Each field tag ( = display label) must be unique. Specifya different field tag. Recompile the form specification.

-2993 Description of Error: There is a circular join path specified in the form.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2994 Description of Error: The form has exceeded the maximum number of joinsbetween tables.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2995 Description of Error: The form has exceeded the maximum number oftables contained in joins.

Corrective Action: Ignore this message. It applies to a feature of PERFORMforms that 4GL does not support.

-2996 Description of Error: The unanticipated error number error-number hasoccurred.

Corrective Action: error-number is an operating system error number. Checkthe UNIX Programmer’s Manual for error information relating to error-number.Contact your System Administrator if you need assistance with this action.You might also contact the Technical Support Department of the companythat supplied your operating system for advice about this error number.Recompile the form specification.

-2997 Description of Error: See error number errno.

Corrective Action: Locate the indicated error message in this appendix.Recompile the form specification.

-2998 Description of Error: Operating system error error-number: string.

Corrective Action: If the error number is between 1-99, check your UNIXProgrammer’s Manual for the error corresponding to the number indicated.Contact your System Administrator if you need assistance with this action.

-2999 Description of Error: SQL server terminated.

Corrective Action: You may have killed the engine daemon by accidentallykilling the wrong process, or an internal error may have overwritten a pipeto the engine. After verifying that the error is not the result of a system limitor problem, please notify the Informix Technical Support Department.

Error Messages 87

Page 902: Manual Informix

-4300 Description of Error: This statement contains too many levels of functioncall nesting.

Corrective Action: A CALL statement can contain only four levels of nestedfunctions. Reduce the number of nested functions in your CALL statement sothat it does not exceed four.

-4301 Description of Error: The program has too many levels of WHILE, FOR,MENU, and/or CASE statements.

Corrective Action: A program can contain only 25 levels of WHILE, FOR,MENU, and/or CASE statements (in any combination). Reduce the number ofnested WHILE, FOR, MENU, and/or CASE statements so that it does notexceed 25.

-4302 Description of Error: The record description is nested too deep.

Corrective Action: Only five levels of nested records can appear in a recorddefinition. Reduce the number of nested records so that it does not exceedfive.

-4304 Description of Error: A different database has already been declared. If yourprogram uses a global definition file, it must contain the same database nameas this one.

Corrective Action: Make sure that the database specified in a global defini-tion file is the same as the database specified in the file containing the MAINroutine.

-4305 Description of Error: The database database-name cannot be found oropened. If the database exists, check the database permissions on the data-base. In addition, check the system permissions on the database directoryand its ascendant directories.

Corrective Action: Check the spelling of the database name. Check that thedatabase name exists in your current directory or in a directory included inyour DBPATH environment variable. Make sure that you have at leastCONNECT permission for the database as well as the appropriate operatingsystem permissions for the database directory.

-4306 Description of Error: The GLOBALS file filename cannot be opened forreading.

Corrective Action: Check that the GLOBALS file exists and that you haveoperating system read permission for the file. If the GLOBALS file is not in thecurrent directory, you must specify the pathname of the file from root orcurrent directory.

88 Error Messages

Page 903: Manual Informix

-4307 Description of Error: The number of variables and/or constants in the dis-play list does not match the number of form fields in the display destination.

Corrective Action: Check the variable-list and the field-list in your DISPLAY orDISPLAY ARRAY statement to make sure that they contain the same numberof items.

-4308 Description of Error: The number of input variables does not match thenumber of form fields in the screen input list.

Corrective Action: Check the variable-list and the field-list in your INPUT orINPUT ARRAY statement to make sure that they contain the same number ofitems.

-4309 Description of Error: Printing cannot be done within a loop or CASE state-ment contained in report headers or trailers.

Corrective Action: Do not include PRINT statements within FOR, WHILE, orCASE statements that appear in FIRST PAGE HEADER, PAGE HEADER, andPAGE TRAILER control blocks.

-4310 Description of Error: Files cannot be printed within report headers or trail-ers.

Corrective Action: Do not include PRINT FILE statements within FIRST PAGEHEADER, PAGE HEADER, and PAGE TRAILER control blocks.

-4311 Description of Error: The variable variable-name was not defined as a record.It cannot be used in this fashion.

Corrective Action: You can use the THRU, THROUGH, or .* notations onlywith records. Define the variable as a record or remove the THRU, THROUGH,or .* notation, as appropriate.

-4312 Description of Error: The NEED statement is allowed only within reports.

Corrective Action: Make sure that the NEED statement only occurs withinthe FORMAT section of a report.

-4313 Description of Error: The NEED statement cannot be used within reportheaders or trailers.

Corrective Action: Remove any NEED statements from FIRST PAGEHEADER, PAGE HEADER, and PAGE TRAILER control blocks.

-4314 Description of Error: The program cannot exit a menu at this point becauseit is not within a MENU statement.

Corrective Action: Make sure that the EXIT MENU keywords appear onlywithin a COMMAND clause of the MENU statement.

Error Messages 89

Page 904: Manual Informix

-4315 Description of Error: The program cannot exit a FOREACH statement at thispoint because it is not within a FOREACH statement.

Corrective Action: Make sure that the EXIT FOREACH keywords appear onlywithin a FOREACH statement.

-4316 Description of Error: The program cannot exit a WHILE statement at thispoint because it is not within a WHILE statement.

Corrective Action: Make sure that the EXIT WHILE keywords appear onlywithin a WHILE statement.

-4317 Description of Error: The program cannot exit a FOR statement at this pointbecause it is not within a FOR statement.

Corrective Action: Make sure that the EXIT FOR keywords appear onlywithin a FOR statement.

-4318 Description of Error: The program cannot exit a CASE statement at this pointbecause it is not within a CASE statement.

Corrective Action: Make sure that the EXIT CASE keywords appear onlywithin a CASE statement.

-4319 Description of Error: The symbol variable-name has been defined more thanonce.

Corrective Action: Make sure that each variable is defined only once in yourGLOBALS, MAIN, FUNCTION, or REPORT statement.

-4320 Description of Error: The symbol table-name is not the name of a table in thespecified database.

Corrective Action: Check the spelling of table-name and make sure that it isa table in the specified database.

-4321 Description of Error: An array may have the maximum of three dimensions.

Corrective Action: Make sure that the array has no more than threedimensions.

-4322 Description of Error: The symbol column-name is not the name of a columnin the specified database.

Corrective Action: Check the spelling of column-name, and make sure that itappears in a table of the specified database.

90 Error Messages

Page 905: Manual Informix

-4323 Description of Error: The variable variable-name is too complex a type to beused in an assignment statement.

Corrective Action: You can assign a value only to a variable that has a simpletype. If you are assigning a value to an element of an array or record, makesure that it has a simple type.

-4324 Description of Error: The variable variable-name is not a character type, andcannot be used to contain the result of concatenation.

Corrective Action: Change the data type of the variable to CHAR so that itcan store the string that results from concatenation.

-4325 Description of Error: The source and destination records in this recordassignment statement are not compatible in types and/or lengths.

Corrective Action: In the statement LET a.* = b.* , each element in recorda must have a data type which is compatible with the data type of the corre-sponding element in record b.

-4326 Description of Error: A NULL value may not be applied to substrings.

Corrective Action: A NULL value can be assigned to a string but not to a sub-string. Remove the subscript(s) if you want to assign a NULL value to thestring.

-4327 Description of Error: The variable variable-name is not of type INTEGER orSMALLINT. It cannot be used as a loop index.

Corrective Action: Change the type of the variable to INTEGER or SMALLINTif you want to use it as a loop index.

-4328 Description of Error: The variable variable-name has too complex a type to beused as the destination of a return from a function.

Corrective Action: You must return values to variables that have simpletypes. If you have specified a record in the RETURNING clause of a CALLstatement, remember to include the THRU, THROUGH, or .* shorthand afterthe record name, and make sure that all the record elements referenced in thisway have simple types.

-4329 Description of Error: The variable variable-name is not a record. Only recordvariables may be expanded using the .* or THROUGH shorthand.

Corrective Action: Change the variable to a record or eliminate theTHROUGH, THRU, or .* notation as appropriate.

Error Messages 91

Page 906: Manual Informix

-4330 Description of Error: RETURN statements can be executed only withinfunctions.

Corrective Action: Make sure that the RETURN keyword appears onlywithin a FUNCTION statement.

-4331 Description of Error: Only variables of type INTEGER or SMALLINT may beused to index display fields.

Corrective Action: Change the type of the variable to INTEGER or SMALLINTif you want to use it to index display fields.

-4332 Description of Error: The LET statement must have at least one sourceexpression.

Corrective Action: Make sure that one or more valid expressions appears tothe right of the equal sign (=) in a LET statement.

-4333 Description of Error: The function function-name has already been calledwith a different number of parameters.

Corrective Action: Make sure that you specify the same number of parame-ters each time you call a function.

-4334 Description of Error: The variable variable-name in its current form is toocomplex to be used in this statement.

Corrective Action: You can use only variables that have simple types. If youhave specified a record in the statement, remember to include the THRU,THROUGH, or .* shorthand after the record name, and make sure that all therecord elements referenced in this way have simple types.

-4335 Description of Error: The symbol variable-name is not an element of therecord record-name.

Corrective Action: Make sure that the variable is listed as an element of therecord in the appropriate DEFINE statement.

-4336 Description of Error: The parameter variable-name has not been definedwithin the function or report.

Corrective Action: You must use the DEFINE statement to declare all param-eters passed as arguments to a function or report.

-4338 Description of Error: The symbol variable-name has already been definedonce as a parameter.

Corrective Action: Make sure that each parameter is defined only once in afunction or report.

92 Error Messages

Page 907: Manual Informix

-4339 Description of Error: 4GL has run out of data space memory.

System Action: The program stops and running transactions are rolled back.

Corrective Action: Divide your program into smaller modules, or reduce thecomplexity of the program.

-4340 Description of Error: The variable variable-name is too complex a type to beused in an expression.

Corrective Action: You can use only variables that have simple types inexpressions. If you have specified an element of a record or array, make surethat it has a simple type.

-4341 Description of Error: Aggregate functions are only allowed in reports andSELECT statements.

Corrective Action: You can use aggregate functions like SUM and AVG onlyin reports and in expressions that appear in SELECT statements.

-4342 Description of Error: PAGENO and LINENO are allowed only in reports.

Corrective Action: Make sure that the PAGENO and LINENO statementsonly occur within the FORMAT section of a report.

-4343 Description of Error: Subscripting cannot be applied to the variable vari-able-name because it is not a character or array variable.

Corrective Action: Check the spelling of the variable name. Define vari-able-name as a character or array variable or remove the subscript, as appro-priate.

-4344 Description of Error: The variable variable-name cannot be used with sub-strings because it is not a character variable.

Corrective Action: Check the data type of the variable. If variable-name is nota character variable, remove the subscript(s) or change the type of the vari-able, as appropriate.

-4345 Description of Error: The variable variable-name has already had substringsapplied to it.

Corrective Action: Rewrite the statement so that only one substring (repre-sented by the notation [a, b]) appears after the variable name.

Error Messages 93

Page 908: Manual Informix

-4346 Description of Error: Subscripts may contain only INTEGER or SMALLINTvariables.

Corrective Action: Check the spelling of the variable name(s). Make surethat each variable is defined as an INTEGER or SMALLINT if you want to useit as a subscript.

-4347 Description of Error: The variable variable-name is not a record. It cannotreference record elements.

Corrective Action: Check the spelling of the variable name. Make sure thatthe variable is defined as a record before you add a suffix (.variable-name) to it.

-4348 Description of Error: This type of aggregate must be applied to an expres-sion, not ‘*’. Only PERCENT and COUNT aggregates use ‘*’.

Corrective Action: Use an expression instead of an asterisk (*) with the SUM,AVG, MIN, and MAX aggregates.

-4349 Description of Error: The PERCENT and COUNT report aggregates cannot beused with an expression.

Corrective Action: Use an asterisk (*) instead of an expression with thePERCENT and COUNT aggregates.

-4350 Description of Error: The program cannot continue a FOR loop at this timebecause it is not within a FOR loop.

Corrective Action: Make sure that the CONTINUE FOR keywords appearonly within a FOR statement.

-4351 Description of Error: The program cannot continue a WHILE loop at thistime because it is not within a WHILE loop.

Corrective Action: Make sure that the CONTINUE WHILE keywords appearonly within a WHILE statement.

-4352 Description of Error: The program cannot continue a FOREACH loop at thistime because it is not within a FOREACH loop.

Corrective Action: Make sure that the CONTINUE FOREACH keywordsappear only within a FOREACH statement.

-4356 Description of Error: A page header has already been specified within thisreport.

Corrective Action: Change the FORMAT section of your report so that itcontains only one PAGE HEADER control block.

94 Error Messages

Page 909: Manual Informix

-4357 Description of Error: A page trailer has already been specified within thisreport.

Corrective Action: Change the FORMAT section of your report so that itcontains only one PAGE TRAILER control block.

-4358 Description of Error: A first page header has already been specified withinthis report.

Corrective Action: Change the FORMAT section of your report so that it con-tains only one FIRST PAGE HEADER control block.

-4359 Description of Error: An ON EVERY ROW clause has already been specifiedwithin this report.

Corrective Action: Change the FORMAT section of your report so that itcontains only one ON EVERY ROW control block.

-4360 Description of Error: An ON LAST ROW clause has already been specifiedwithin this report.

Corrective Action: Change the FORMAT section of your report so that itcontains only one ON LAST ROW control block.

-4361 Description of Error: Group aggregates can occur only in AFTER GROUPclauses.

Corrective Action: Make sure that the GROUP COUNT, GROUP PERCENT,GROUP SUM, GROUP AVG, GROUP MIN, and GROUP MAX aggregates appearonly in AFTER GROUP control blocks.

-4362 Description of Error: The report cannot skip to the top of page while in aheader or trailer.

Corrective Action: Remove SKIP TO TOP OF PAGE statements from FIRSTPAGE HEADER, PAGE HEADER, and PAGE TRAILER control blocks.

-4363 Description of Error: The report cannot skip lines while in a loop within aheader or trailer.

Corrective Action: Remove SKIP statements from FOR and WHILE loops thatappear in FIRST PAGE HEADER, PAGE HEADER, and PAGE TRAILER controlblocks.

-4364 Description of Error: There are a non-matching number of variables anddatabase columns in this statement.

Corrective Action: Make sure that the number of variables in the statementis the same as the number of database columns.

Error Messages 95

Page 910: Manual Informix

-4365 Description of Error: Deferments of interrupt or quit may be executed onlyin the main program.

Corrective Action: Make sure that DEFER INTERRUPT and DEFER QUIT state-ments appear only in the MAIN section of your program.

-4366 Description of Error: There are a non-matching number of variables anddatabase columns in this statement.

Corrective Action: Make sure that the number of variables in the statementis the same as the number of database columns.

-4367 Description of Error: Interrupt has already been deferred once in the MAINprogram. Each main program may defer interrupt only once.

Corrective Action: Make sure that the DEFER INTERRUPT statement appearsonly once, and then only in the MAIN section of your program. (Oncedeferred, Interrupt signals cannot be reactivated.)

-4368 Description of Error: Quit has already been deferred once in the MAINsection of your program. Each main program may defer quit only once.

Corrective Action: Make sure that the DEFER QUIT statement appears onlyonce, and then only in the MAIN section of your program. (Once deferred,Quit signals cannot be reactivated.)

-4369 Description of Error: The symbol variable-name does not represent a definedvariable.

Corrective Action: Make sure that you define the variable in a DEFINE state-ment in the appropriate part of your program.

-4370 Description of Error: The variable variable-name cannot be used invalidation.

Corrective Action: You can validate only variables that have simple types. Ifyou have specified a record in the statement, remember to include the THRU,THROUGH, or .* notation after the record name, and make sure that all recordelements referenced in this way have simple types.

-4371 Description of Error: Cursors must be uniquely declared within oneprogram module.

Corrective Action: Make sure that each cursor is declared only once in aprogram file.

96 Error Messages

Page 911: Manual Informix

-4372 Description of Error: The cursor cursor-name has not yet been declared inthis program module. It must be declared before it can be used.

Corrective Action: You must use the DECLARE statement to declare a cursorin each module before you can use it in statements such as FOREACH, OPEN,and FETCH.

-4373 Description of Error: A grammatical error has been found on line line-num-ber, character character-number. The construct is not understandable in its con-text.

Corrective Action: When INFORMIX-4GL encounters a grammatical error, itinserts a marker in the .err file just past the point where the parser detectedthe error. Check the syntax of the marked statement.

-4375 Description of Error: The page length is too short to cover the specified pageheader and trailer lengths.

Corrective Action: Make sure that the total number of lines required for thepage header and trailer do not exceed the default page length or the lengthspecified in the PAGE LENGTH statement. Change the page header and traileror the page length as appropriate.

-4376 Description of Error: The temporary file filename cannot be created forwriting.

Corrective Action: Check that you have permission to write a file in /tmp orthe directory specified by the DBTEMP environment variable. Check thatthere is enough space in the directory where the temporary file will reside.Contact your System Administrator if you need help with these actions.

-4377 Description of Error: The output file filename cannot be created or opened.

Corrective Action: Check that you have permission to write a file in thedirectory where the output file will be created. Contact your System Admin-istrator if you need help with this action.

-4378 Description of Error: No input file was specified.

Corrective Action: Make sure that you specify an input filename.

-4379 Description of Error: The input file filename cannot be opened.

Corrective Action: Check the spelling of the input filename. Check that thefile exists in the current directory. Check that you have operating system readpermission for the input file.

Error Messages 97

Page 912: Manual Informix

-4380 Description of Error: The listing file filename cannot be created.

Corrective Action: Check that you have operating system write permissionin the directory where the listing file will be created. Contact your SystemAdministrator if you need help with this action.

-4381 Description of Error: The input file filename has an invalid extension. Thefilename must have .4gl as the extension.

Corrective Action: Rename the input file so that it has the extension .4gl.

-4382 Description of Error: Record variables that contain array type elements maynot be referenced by the ".*" or THROUGH shorthand, or used as a functionparameter.

Corrective Action: Rewrite your statement so that record variables witharray components do not appear with the THRU, THROUGH, or .* short-hands or as function parameters.

-4383 Description of Error: The elements element-name1 and element-name2 do notbelong to the same parent record.

Corrective Action: Check the spelling of the element names and make surethat both elements belong to the same record.

-4384 Description of Error: The symbol element-name does not represent the ele-ment of any record.

Corrective Action: Check the spelling of element-name and make sure that itbelongs to the specified record.

-4385 Description of Error: Report aggregates may not be nested.

Corrective Action: Rewrite your statement so that report aggregates are notnested.

-4386 Description of Error: There are too many ORDER BY fields in this report. Themaximum number is eight.

Corrective Action: Reduce the number of ORDER BY fields to eight or less.

-4387 Description of Error: The right margin must be greater than the left margin.

Corrective Action: Check that the RIGHT MARGIN value is greater than theLEFT MARGIN value.

98 Error Messages

Page 913: Manual Informix

-4388 Description of Error: There is one BEFORE GROUP OF clause and one AFTERGROUP OF clause allowed for each report input parameter.

Corrective Action: You can use only one BEFORE GROUP OF control blockand one AFTER GROUP OF control block for each report parameter. You mustcombine multiple BEFORE GROUP OF or AFTER GROUP OF control blocks forthe same parameter into a single control block.

-4389 Description of Error: There are too many levels of nesting of IF statementsin this report.

Corrective Action: You have exceeded the maximum of five levels of nestedIF statements. Remove one or more statements.

-4391 Description of Error: When doing INPUT BY NAME or INPUT ARRAY, theBEFORE/AFTER field names can be specified only by the field name suffix.Screen array and screen record elements are not allowed.

Corrective Action: You cannot include a prefix when specifying a field namein a BEFORE FIELD or AFTER FIELD clause of an INPUT or INPUT ARRAY state-ment. (A prefix consists of table-name, formonly, screen-record, orscreen-record[n] followed by a period.)

-4392 Description of Error: The 4GL compiler has run out of data space memoryto contain the 4GL program symbols. If the program module is very large,dividing it into separate modules may alleviate the situation.

Corrective Action: Divide your program into smaller programs or reducethe complexity of your program.

-4393 Description of Error: The MENU statement has exceeded the maximumnumber of selections.

Corrective Action: Reduce the number of COMMAND clauses in the MENUstatement so that it does not exceed the limit of 25.

-4394 Description of Error: The MENU statement has two or more selections usingthe key-name key.

Corrective Action: The user selects a menu option by typing one of the let-ters in a key list (if a KEY clause for the menu option is present) or by typingthe first letter of the menu option (if a KEY clause for the option is notpresent). Rewrite the MENU statement so that the letter for selecting eachmenu option is unique.

Error Messages 99

Page 914: Manual Informix

-4395 Description of Error: There are too many subscripts specified with a data-base column name.

Corrective Action: You can use no more than two subscripts with databasecolumns of type CHAR.

-4396 Description of Error: The MENU declaration at line lineno is not terminated.

Corrective Action: Make sure that you conclude the MENU statement withthe END MENU keywords.

-4397 Description of Error: The IF statement at line lineno is not terminated.

Corrective Action: Make sure that you conclude the IF statement with theEND IF keywords.

-4398 Description of Error: The CASE statement at line lineno is not terminated.

Corrective Action: Make sure that you conclude the CASE statement withthe END CASE keywords.

-4399 Description of Error: The WHILE statement at line lineno is not terminated.

Corrective Action: Make sure that you conclude the WHILE statement withthe END WHILE keywords.

-4400 Description of Error: The FOR statement at line lineno is not terminated.

Corrective Action: Make sure that you conclude the FOR statement with theEND FOR keywords.

-4401 Description of Error: A concatenation operation has created a string toolong to fit in the destination string variable.

Corrective Action: When possible, use the CLIPPED keyword to eliminatetrailing blanks from the strings you want to concatenate. If the resultantstring still exceeds the length of the character variable, increase the size of thecharacter variable.

-4402 Description of Error: In this type of statement, subscripting may be appliedonly to array variables to select individual array elements.

Corrective Action: Make sure that the variable is defined as an array beforeyou use it with subscripts in this type of statement.

100 Error Messages

Page 915: Manual Informix

-4403 Description of Error: The number of dimensions for the variable vari-able-name does not match the number of subscripts.

Corrective Action: Rewrite the statement so that the number of subscriptsafter the array name is the same as the number of dimensions in the arraydefinition.

-4406 Description of Error: There is an unmatched quote in the above line.

Corrective Action: Check that all strings begin and end with a quote.

-4407 Description of Error: There is an unprintable character in the above line.

Corrective Action: Remove the unprintable character (usually a controlcharacter). You may have to retype the line.

-4408 Description of Error: There is a quoted string that is too long in the aboveline.

Corrective Action: A quoted string cannot exceed 80 characters. Reduce thelength of the quoted string or, if appropriate, divide it into shorter stringsseparated by commas.

-4409 Description of Error: There is an invalid character in the above line.

Corrective Action: Remove the invalid character (often a non-printable con-trol character).

-4410 Description of Error: There is a numeric constant in the previous line that istoo large or too small.

Corrective Action: Make sure that the number has no more than 50 charac-ters, and that it is within the acceptable range for its data type. For SMALLINTvalues, this range is from -32,767 to -32,767. An INTEGER must have an abso-lute value in the range from zero to 2,147,483,647. The absolute value of aDECIMAL number can range from from 10-128 to 10126. Also check that youhave not inadvertently entered a letter in place of a digit.

-4411 Description of Error: There is an alphanumeric identifier that is too long inthe above line.

Corrective Action: Make sure that an alphanumeric identifier is no longerthan 50 characters.

-4412 Description of Error: Values from the RUN command can be returned onlyto INTEGER or SMALLINT variables.

Corrective Action: Make sure that the variables that appear in theRETURNING clause of a RUN statement are defined as INTEGER or SMALLINT.

Error Messages 101

Page 916: Manual Informix

-4413 Description of Error: The label label-name has already been defined withinthis MAIN program or function.

Corrective Action: Make sure that each label is defined only once in theMAIN program or function.

-4414 Description of Error: The label label-name has been used but has never beendefined within the above main program or function.

Corrective Action: Make sure that you define each label with the LABELstatement before using it in the MAIN program or function.

-4415 Description of Error: An ORDER BY or GROUP item specified within a reportmust be one of the report parameters.

Corrective Action: Make sure that only report parameters appear in ORDERBY, BEFORE GROUP OF, or AFTER GROUP OF statements in a report. You can-not use global or local variables.

-4416 Description of Error: There is an error in the validation string: ‘‘string’’.

Corrective Action: Change the appropriate DEFAULT or INCLUDE value inthe syscolval table.

-4417 Description of Error: This type of statement can be used only in a report.

Corrective Action: Make sure that statements like PRINT, SKIP, and NEEDappear only in a REPORT statement.

-4418 Description of Error: The variable used in the INPUT ARRAY statement mustbe an array.

Corrective Action: Check the spelling of the variable name and make surethat it has been defined as an array.

-4419 Description of Error: The variable used in the CONSTRUCT statement mustbe a character variable.

Corrective Action: Make sure that the variable that appears after theCONSTRUCT keyword has been defined as a large CHAR variable.

-4420 Description of Error: The number of lines printed in the IF part of an IF-THEN-ELSE statement of a header or trailer clause must equal the number oflines printed in the ELSE part.

Corrective Action: Add or remove lines as necessary so that number of linesprinted in the IF part is the same as the number of lines printed in the ELSEpart of the IF-THEN-ELSE statement.

102 Error Messages

Page 917: Manual Informix

-4421 Description of Error: You may not use an INPUT statement within anotherINPUT statement or PROMPT statement, even if it is enclosed within a condi-tional or looping statement.

Corrective Action: Remove any INPUT statements that appear within anINPUT or PROMPT statement.

-4422 Description of Error: You may not use a CONSTRUCT statement withinanother INPUT statement. This includes situations when CONSTRUCT isenclosed within a conditional or looping statement. You must call a functionthat executes the CONSTRUCT statement.

Corrective Action: Move any CONSTRUCT statement within an INPUTstatement to a function, and call that function from the INPUT statement.

-4423 Description of Error: The CLIPPED and USING options for the DISPLAYstatement may not be used when displaying to a form field.

Corrective Action: Remove all references to CLIPPED and USING fromDISPLAY TO or DISPLAY BY NAME statements. You can substitute for USINGan appropriate format string with the FORMAT attribute, and recompile theform.

-4424 Description of Error: The variable variable-name has not been defined as arecord.

Corrective Action: Make sure that the variable is defined as a record beforeusing it with the THRU, THROUGH, or .* notation.

-4425 Description of Error: The variable variable-name has not been defined LIKEthe table table-name.

Corrective Action: Define the variable with the RECORD LIKE keywords ifyou want to use it in an UPDATE statement.

-4426 Description of Error: The PRINT statement may be used only within reports.If you wish to print without screen positioning, use the DISPLAY statementwithout any field or screen destination.

Corrective Action: Replace all PRINT statements that appear outside ofreports with DISPLAY statements. Use the DISPLAY TO or DISPLAY BY NAMEstatement to display information in a display field on a screen form, theDISPLAY AT statement to display information at a specified row and columnon the screen, or the DISPLAY statement to display information withoutscreen positioning.

Error Messages 103

Page 918: Manual Informix

-4427 Description of Error: The COLUMN feature for the DISPLAY statement maybe used only when displaying without screen or field destination.

Corrective Action: Remove the COLUMN function from the display list ofany DISPLAY AT, DISPLAY TO, or DISPLAY BY NAME statement.

-4428 Description of Error: You may not use a PROMPT statement within an INPUTor PROMPT statement, even if it is enclosed within a conditional or loopingstatement.

Corrective Action: Remove any PROMPT statements that appear within anINPUT or PROMPT statement.

-4429 Description of Error: Report and function parameters cannot be arrays.

Corrective Action: Remove any arrays from the parameter lists of functionsor reports.

-4430 Description of Error: Record parameters for a report cannot containelements that are arrays.

Corrective Action: Rewrite your program so that record parameters forreports do not contain array elements.

-4432 Description of Error: An element in a GROUP clause must be a member ofthe ORDER BY clause.

Corrective Action: Rewrite the statement so that each element in a BEFOREGROUP OF or AFTER GROUP OF clause also appears in the ORDER BY clause.

-4433 Description of Error: A variable used in the above statement must be of typeCHAR.

Corrective Action: The filename in the REPORT TO ‘‘filename’’ statementmust evaluate to a CHAR variable, or the program in the REPORT TO PIPE‘‘program’’ statement must evaluate to a CHAR variable.

-4434 Description of Error: The limits of the INFORMIX-4GL Demo Version havebeen exceeded. Please call Informix Software, Inc. at (415) 926-6300 for licens-ing information.

Corrective Action: A program compiled using the demonstration version ofINFORMIX-4GL can contain only one module with no more than 150 INFOR-MIX-4GL statements. Check that you have not exceeded the statement limitor called a function that is not included in the module.

Please contact your Informix Sales Representative for information about afull INFORMIX-4GL development license.

104 Error Messages

Page 919: Manual Informix

-4435 Description of Error: An acceptable hyphenated key format is control-x,where x is any letter except a, d, h, l, r, or x.

Corrective Action: You cannot redefine a function key as one of the editingkeys for an INPUT, INPUT ARRAY, or CONSTRUCT statement. Select analternate key.

-4437 Description of Error: All table names in the SELECT list must be the same asthe table names in the FROM clause.

Corrective Action: Check that you have not misspelled the name of a tablein the SELECT list.

-4438 Description of Error: You cannot SELECT into a substring of a charactervariable.

Corrective Action: Remove the substring from the CHAR variable in theINTO clause of the SELECT statement.

-4439 Description of Error: You cannot SELECT into record record-name becauseelement element is a record or an array.

Corrective Action: Edit the SELECT statement in your program.

-4440 Description of Error: element-name precedes element-name in recordrecord-name and must also precede it when used with the THROUGHshorthand.

Corrective Action: Re-order the elements used with the THROUGH keywordto match the order of elements in the record.

-4441 Description of Error: The ISAM cursor cursor-name has not yet been declaredin this program module. It must be declared before it can be used.

Corrective Action: Check the spelling of cursor_name and that you havephysically declared the cursor before making reference to it.

-4442 Description of Error: fetch-direction is not a recognized row selector in theISAM FETCH statement.

Corrective Action: fetch-direction must evaluate to one of the following:FIRST, LAST, CURRENT, RELATIVE integer, ABSOLUTE integer, NEXT, PRIOR,PREVIOUS, or ROWID integer. Check the spelling of fetch-direction.

-4443 Description of Error: Only constants and variables of type INTEGER orSMALLINT may be used to specify the size and/or position of windows.

Corrective Action: Check that the values in the WITH and AT clauses of theOPEN WINDOW statement evaluate to type INTEGER or SMALLINT.

Error Messages 105

Page 920: Manual Informix

-4444 Description of Error: Too many colors specified for window.

Corrective Action: You can include only one color in the ATTRIBUTE clauseof the OPEN WINDOW statement.

-4445 Description of Error: You may not open or close window SCREEN.

Corrective Action: You cannot execute an OPEN WINDOW screen or CLOSEWINDOW screen statement. Edit your INFORMIX-4GL program.

-4446 Description of Error: Key value key-value may not be used in this context.

Corrective Action: Choose an acceptable key value and recompile theprogram. Acceptable key values are f1 through f36, ESC, ESCAPE, the Inter-rupt key, or CTRL-k where k is any character except a, d, h, l, r, or x. Some sys-tems also reserve CTRL-S and CTRL-Q for special purposes.

-4447 Description of Error: Value is not a recognized key value.

Corrective Action: Choose an acceptable key value and recompile the pro-gram. Acceptable key values are f1 through f36, ESC, ESCAPE, the Interruptkey, or CTRL-X where x is any character except a, d, h, l, r, or x.

-4448 Description of Error: Cannot open the file filename for reading or writing.

Corrective Action: Check that the file filename exists and that you havepermission to read or write to it.

-4452 Description of Error: The function function-name has already been defined.

Corrective Action: Check your code to make sure that the function has notbeen defined more than once. Recompile the program.

-4453 Description of Error: The size of the global string table has exceeded thelimit of 32767.

Corrective Action: Reduce the number of global variables or reduce thelength of each global variable and recompile the program.

-4454 Description of Error: The size of the local string table has exceeded the limitof 32767.

Corrective Action: Decrease the length or the number of strings and localvariables. Recompile the program.

-4456 Description of Error: This help number is not acceptable or reserved.

Corrective Action: Use help numbers in the range -32,767 to 32,767.

106 Error Messages

Page 921: Manual Informix

-4457 Description of Error: You may have at most 4 keys in the key list.

Corrective Action: Reduce the number of keys to four or less when using theKey clause in the COMMAND statement of MENU.

-4458 Description of Error: One dimension of this array has exceeded the limitof 32767.

Corrective Action: Split the array so that the maximum dimension of thearray is less than 32,767. Recompile the form specification.

-4459 Description of Error: The total size of an array cannot exceed num.

Corrective Action: Decrease the size of the array to the hardware limit spec-ified by num and recompile the form specification.

-4460 Description of Error: Invalid attribute name string.

Corrective Action: Check the spelling of the attribute name. Allowableattribute names are WHITE, YELLOW, MAGENTA, RED, CYAN, GREEN, BLUE,BLACK, REVERSE, BLINK, UNDERLINE, and those that have been added to thecolornames file. Correct the attribute statement and recompile the program.

-4461 Description of Error: Line num in the colornames file must have the form"<color> 0-9".

Corrective Action: The compiler cannot read the colornames file located ineither the current directory or $INFORMIXDIR/incl because a line does nothave the specified format. Check the spelling and syntax for line num in thecolornames file and recompile the program.

-4462 Description of Error: Scroll direction must be either UP or DOWN.

Corrective Action: Check the spelling of the scroll direction.

-4463 Description of Error: You may not use NEXT FIELD outside of an INPUTstatement.

Corrective Action: Place NEXT FIELD inside an INPUT statement or INPUTARRAY statement and recompile.

-4464 Description of Error: The number of columns must match the number ofvalues in the SET clause of an UPDATE statement.

Corrective Action: Make sure that the SET clause includes as many columnsin the column-list as the number of values that are produced by the expr-list.

Error Messages 107

Page 922: Manual Informix

-4465 Description of Error: The FOREACH statement at line num is not terminated.

Corrective Action: Make sure that each FOREACH keyword is eventuallyfollowed by a corresponding END FOREACH keyword that terminates theFOREACH loop. EXIT FOREACH is not equivalent to END FOREACH.

-4466 Description of Error: Column column-name of table table-name has too manydefault values.

Corrective Action: Only one default value is allowed for a column. Whilecompiling the INITIALIZE LIKE statement, the compiler has found more than1 default value for the specified column. These defaults are put into thesyscolval table by the upscol utility. Use the upscol utility to remove all butone of the values and recompile the program.

-4467 Description of Error: Array array-name must have just 1 dimension forINPUT ARRAY or DISPLAY ARRAY.

Corrective Action: Check that the array specified in the INPUT ARRAY orDISPLAY ARRAY statement has only one dimension. Remove all other dimen-sions and recompile the program.

-4468 Description of Error: Column column-name does not belong to tabletable-name.

Corrective Action: Check the spelling of column column-name. Check thatcolumn column-name is located in the database table.

-4469 Description of Error: FOR UPDATE cannot be used with SCROLL cursors.

Corrective Action: Do not DECLARE a SCROLL cursor with a FOR UPDATEclause.

-4470 Description of Error: A SCROLL cursor was not declared.

Corrective Action: Do not use a FETCH direction statement where direction isanything other than a NEXT with a non-scrolling cursor. Declare the cursor asa SCROLL cursor to FETCH FIRST, FETCH PREVIOUS, etc.

-4471 Description of Error: UPDATEs may not be used with singleton selects.

Corrective Action: Remove the FOR UPDATE clause and recompile, orDECLARE a cursor for UPDATE with a WHERE CURRENT OF clause or use thecursor instead.

-4472 Description of Error: The INPUT statement at line num is not terminated.

Corrective Action: Add an END INPUT statement to match the specifiedINPUT statement.

108 Error Messages

Page 923: Manual Informix

-4473 Description of Error: The DISPLAY ARRAY statement at line num is notterminated.

Corrective Action: Add an END DISPLAY statement to match the specifiedDISPLAY statement.

-4474 Description of Error: The PROMPT statement at line num is not terminated.

Corrective Action: Add an END PROMPT statement to match the specifiedPROMPT statement.

-4475 Description of Error: name may not be used as both a function name and avariable name.

Corrective Action: Rename either the function or the variable, and recom-pile the program.

-4476 Description of Error: Record members may not be used with database col-umn substring. Possible misspelling or usage of undefined host variables.

Corrective Action: This statement uses an expression of the formname1.name2[...], where name2 is either a column name, in which case youcannot specify the substring, or else a variable that has not been defined.Check the spelling of name1.name2, or remove the brackets, and recompile theprogram.

-4477 Description of Error: The variable variable-name is an array. You must specifyone of its elements in this statement.

Corrective Action: Use subscripts to specify an element, and recompile theprogram. Make sure that you specify only one element of the array with thenotation array-name [element-number]. Do not specify the entire array.

-4478 Description of Error: The size of the local variables used in this function hasexceeded the 32K per function limit.

Corrective Action: Reduce the size of the function’s local variables, andrecompile.

-4479 Description of Error: Warning: non-ANSI comment indicator. Use ‘‘--’’ forANSI compatibility.

Corrective Action: If you want your source code to conform to ANSI Level Istandards for SQL, substitute ‘‘--’’ for the braces ( { } ) or pound ( # ) symbolcomment indicator.

Error Messages 109

Page 924: Manual Informix

-4480 Description of Error: Warning: this statement is not compatible with ANSIStandard SQL syntax.

Corrective Action: The statement is an extension to the ANSI standard forSQL. If you want your source code to conform to ANSI standards for SQL, youmust edit and recompile your source code to include only ANSI statements.See Chapter 7 of this manual for a list of the Informix extensions to the ANSIstandard syntax for SQL.

-4481 Description of Error: Subscripting cannot be applied to the variable namebecause it is not an array variable. The substring operator cannot be usedwith host variables in this statement.

Corrective Action: Check that name is spelled correctly. Delete any sub-scripts of non-array variables, and recompile.

-4482 Description of Error: BY NAME may not be used with owner names orremote database names.

Corrective Action: The name of a field in a screen form cannot be qualifiedby an owner name, a site name, or a remote database name. In the TABLESsection of the form specification file, specify a table alias that includes thequalifier(s). Use this alias in the BY NAME clause of any 4GL statements thatreference fields linked to columns of the table. Then recompile your form andyour program.

-4483 Description of Error: No more than two subscripts may be used to specify asubstring.

Corrective Action: Delete the extraneous subscript(s), and recompile.

-4484 Description of Error: Cannot specify UNIQUE CONSTRAINT name for TEMPtable.

Corrective Action: You can specify a UNIQUE CONSTRAINT for a TEMPtable, but you cannot specify a name for the constraint. Remove theCONSTRAINT constr-name clause from your CREATE TEMP TABLE statement.

-4501 Description of Error: A parameter count mismatch has occurred betweenthe calling function and the called function.

Corrective Action: Make sure that the number of parameters in the callingstatement is the same as the number of parameters in the called function.

110 Error Messages

Page 925: Manual Informix

-4502 Description of Error: The 4GL program has run out of runtime data spacememory.

System Action: The program stops and running transactions are rolled back.

Corrective Action: Divide your program into smaller modules. Reduce thesize of arrays and character variables. Make sure that no function returns acharacter string longer than 512 characters.

-4503 Description of Error: A function has not returned the correct number of val-ues expected by the calling function.

Corrective Action: Make sure that the number of parameters after theRETURN keyword in the called function is the same as the number of param-eters after the RETURNING keyword in the calling statement.

-4504 Description of Error: A validation error has occurred as a result of theVALIDATE command.

Corrective Action: Make sure that the values of the variables in a VALIDATEstatement conform to the values allowed for the corresponding columns inthe syscolval table.

-4508 Description of Error: PRINT FILE error—cannot open file filename forreading.

Corrective Action: Check that the specified file exists, and that you haveREAD access to it. Contact your System Administrator if you need help withthis action.

-4513 Description of Error: A number used as a DISPLAY AT location or SCROLLcount must be positive.

Corrective Action: Make sure that you use only positive integer expressionsin DISPLAY AT or SCROLL statements.

-4517 Description of Error: Strings of length > 512 cannot be returned from func-tion calls.

Corrective Action: Make sure that a character string returned by a functiondoes not exceed 512 characters.

-4518 Description of Error: The 4GL program cannot allocate any more space fortemporary string storage.

Corrective Action: INFORMIX-4GL cannot allocate more than 512 charactersfor temporary string storage. This error can occur if the nested functions in aCALL statement return strings whose total length exceeds 512 characters.

Error Messages 111

Page 926: Manual Informix

-4524 Description of Error: The program cannot be executed.

Corrective Action: You may have tried to run a program that was not cre-ated by the p-code compiler. Recompile the program. If the problem recurs,call your Informix Representative.

-4527 Description of Error: Undefined opcode in function function-name.

Corrective Action: The p-code file has been corrupted. Recompile theprogram.

-4529 Description of Error: A select statement could not be prepared for selectingrows from a temporary table used for a report.

Corrective Action: Recompile the program. If the problem recurs, call yourInformix Representative.

-4530 Description of Error: Cannot close and free a cursor used to process a report.

Corrective Action: Recompile the program. If the problem reoccurs, callyour Informix Representative.

-4531 Description of Error: The file filename starts with a bad magic number. Youmay have tried to run a file that was not created by the 4GL p-code compiler.

Corrective Action: The p-code file has been corrupted. Recompile theprogram.

-4534 Description of Error: Wordwrap may not be used within report headers ortrailers.

Corrective Action: In the FORMAT section of a report, you cannot use theWORDWRAP keyword in the PAGE HEADER, PAGE TRAILER, or FIRST PAGEHEADER control blocks.

-4600 Description of Error: No form by specified name found.

Corrective Action: Check the spelling of the form name. Check that the formexists in the current directory or in one of the directories specified byDBPATH.

-4601 Description of Error: No 4GL module by specified name found.

Corrective Action: Check the spelling of the module name. Check that themodule exists in the current directory or in one of the directories specified byDBPATH.

112 Error Messages

Page 927: Manual Informix

-4602 Description of Error: No 4GL program by specified name found.

Corrective Action: Check the spelling of the program name. Check that theprogram exists in the 4GL program database.

-4603 Description of Error: No executable 4GL program by specified name found.

Corrective Action: Check the spelling of the program name. Check that theprogram exists in the INFORMIX-4GL program database. Check the setting ofthe DBPATH variable.

-4604 Description of Error: Error(s) found in 4GL module.

Corrective Action: Select the Correct option and correct the errors indicatedby the error messages.

-4607 Description of Error: The following errors were discovered duringcompilation.

Corrective Action: Examine the .err files to determine the problem. Modifythe appropriate INFORMIX-4GL files and recompile. You can use the vi editorto edit file.err to look at the error file and use the Module-Modify option tochange the file and recompile.

-4608 Description of Error: The compilation of the program was not successful.

Corrective Action: Check that you have used the correct syntax for the state-ments in your program. You may have used a reserved word as an identifier.

-4609 Description of Error: Insufficient memory is available to complete programcompilation.

Corrective Action: Divide your program into smaller modules. Recompilethe program.

-4610 Description of Error: Warning(s) found in 4GL module.

Corrective Action: When you compiled with the -ansi option, Informixextensions to ANSI standard syntax were found in your source code. If youwant your source code to conform with ANSI SQL standards, you must editand recompile your source code to include only ANSI statements. SeeChapter 7 of this manual for a list of the Informix extensions to the ANSI stan-dard syntax for SQL.

-4611 Description of Error: There is no 4GL source available for this program.

Corrective Action: Check the program definition file for the names of themodules that make up the program.

Error Messages 113

Page 928: Manual Informix

-4612 Description of Error: Data validation table does not currently exist for thisdatabase.

Corrective Action: If the syscolval table exists, make sure that it resides inthe current directory or in a directory specified by DBPATH. Otherwise, selectthe Yes option to create it.

-4613 Description of Error: Screen display attribute table does not currently existfor this database.

Corrective Action: If the syscolatt table exists, make sure that it resides inthe current directory or in a directory specified by DBPATH. Otherwise, selectthe Yes option to create it.

-4614 Description of Error: A program already exists by this name.

Corrective Action: Make sure that the name of each program is unique.

-4615 Description of Error: Invalid program name.

Corrective Action: A program name cannot exceed ten characters. Makesure that the program name begins with a letter. The rest of the name cancontain any combination of letters, numbers, and underscores (_).

-4616 Description of Error: The 4GL program database does not exist. Pleasecreate via PROGRAM section.

Corrective Action: If the syspgm4gl program database does not exist, createit by using the Program option of the Programmer’s Environment. Ifsyspgm4gl does exist, make sure that it resides in the current directory or ina directory specified by the DBPATH environment variable.

-4617 Description of Error: You may not edit a program located on a differentdevice.

Corrective Action: You cannot specify a pathname to a source file in a direc-tory that is not on the device that holds your current directory. Use a systemutility to copy the source file to your current directory (or to a directory onthe current device).

-4618 Description of Error: An error has occurred in accessing the requested file.

Corrective Action: Something prevented your access to the file. This couldbe a hardware problem, your file system could be out of disk space, or youmay not have permission to access the file or the directory. Contact yourSystem Administrator.

114 Error Messages

Page 929: Manual Informix

-4620 Description of Error: ESQL/C from Informix Software is not installed on thesystem.

Corrective Action: You must purchase and install INFORMIX-ESQL/C if youwant your INFORMIX-4GL application program to contain the .ec files. Oth-erwise, you must remove all mention of the .ec files in the program definition.

-4621 Description of Error: An error occurred while writing to output file filename.

Corrective Action: Something prevented your access to the file. This couldbe a hardware problem, your file system could be out of disk space, or youmay not have permission to access the file or the directory. Contact yourSystem Administrator.

-4622 Description of Error: No runable 4GL program by specified name found.

System Action: INFORMIX-4GL prompts you to enter the name of an exist-ing executable program.

Corrective Action: Check the spelling of the program name. Check that theexecutable program exists in the current directory or in one of the directoriesspecified by DBPATH.

-4623 Description of Error: memory allocation error

Corrective Action: The process was unable to acquire the amount of mem-ory which it requested. Divide your program into smaller modules, or reducethe complexity of the program.

-4624 Description of Error: Owner name user has exceeded 8 characters in length.

Corrective Action: The name of an owner can have up to eight (8) characters.Check to make sure that the correct name was supplied.

-4625 Description of Error: FIXTIME FAILED

Corrective Action: This is an internal error. After verifying that the error hasnot been generated as the result of a system limit or problem, please notifythe Informix Technical Support Department.

-4626 Description of Error: Could not open file filename.

Corrective Action: Check the directory listing for this file. It might not exist,or permissions might be set that prevent the program from reading the file.

-4627 Description of Error: The program cannot exit an INPUT statement at thispoint because it is not within an INPUT statement.

Corrective Action: See if you inadvertently added or deleted statementswhen you edited your source file.

Error Messages 115

Page 930: Manual Informix

-4628 Description of Error: The program cannot exit a DISPLAY ARRAY statementat this point because it is not within a DISPLAY ARRAY statement.

Corrective Action: See if you inadvertently added or deleted statementswhen you edited your source file.

-4629 Description of Error: Load from file filename failed.

Corrective Action: A conversion error occurred, or there was insufficientspace to complete the load. Check your disk space availability and the filesize.

-4630 Description of Error: Unload to file filename failed.

Corrective Action: A conversion error occurred or there was insufficientspace to complete the load. Check your disk space availability and the filesize.

-4631 Description of Error: Startfield of DATETIME or INTERVAL qualifiers mustcome earlier in the time-list than its endfield.

Corrective Action: You may have reversed the order of qualifiers, or substi-tuted one keyword for another in specifying the qualifiers. Specify the largestunit first, and the smallest last.

-4632 Description of Error: Parenthetical precision of FRACTION must be between1 and 5. No precision can be specified for other time units.

Corrective Action: You either specified an out-of-range precision for theFRACTION field, or else you attempted to specify non-default precision for aDATETIME field other than FRACTION. See Appendix J for the distinctionbetween INTERVAL and DATETIME data types.

-4633 Description of Error: DATETIME units can only be YEAR, MONTH, DAY,HOUR, MINUTE, SECOND, and FRACTION.

Corrective Action: Substitute a valid qualifier from among the keywordslisted in the error message for whatever keyword you invented or mis-spelled. Do not append ‘‘S’’ to a keyword.

-4634 Description of Error: Symbol name must be a SQL database item name—either a database name, a table name or a column name.

Corrective Action: Check your spelling of the identifier of the SQL object.You may be in the wrong database.

116 Error Messages

Page 931: Manual Informix

-4635 Description of Error: Cannot create temporary file filename to contain a blobvariable.

Corrective Action: An I/O error occurred while trying to write the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

-4638 Description of Error: The maximum size for varchar must be between 1and 255.

Corrective Action: You can use the CHAR data type to store strings largerthan 255 bytes.

-4639 Description of Error: Real column name cannot be specified here. Thesymbol "*" is expected instead.

Corrective Action: Substitute the asterisk ( * ) notation for a column name orlist of names.

-4640 Description of Error: Table name is expected here.

Corrective Action: Specify the name of a table in the current database.

-4641 Description of Error: Column name is expected here.

Corrective Action: Specify the name of a column in the current database.You must prefix it with the table identifier, if other columns in the same data-base have the same name.

-4642 Description of Error: Subscripting is NOT allowed here.

Corrective Action: Modify your code so that no subscript appears in thisstatement, and recompile.

-4643 Description of Error: A field in the INTERVAL qualifier is out of range. Theacceptable ranges are from YEAR to MONTH and from DAY to FRACTION.

Corrective Action: You cannot include both MONTH and smaller fields, orDAY and larger fields, in the precision of an INTERVAL value.

-4644 Description of Error: The HELP and ATTRIBUTE clauses each can be speci-fied only once.

Corrective Action: Delete all but one clause of each type from the statement,and recompile.

-4645 Description of Error: 4GL does not support returning a blob variable.

Corrective Action: Rewrite the function so that no BYTE nor TEXT valueappears in the RETURNING clause, and recompile.

Error Messages 117

Page 932: Manual Informix

-4646 Description of Error: The specified WORDWRAP RIGHT MARGIN value isout of range. It must be greater than or equal to the current column and lessthan or equal to the report’s right margin.

Corrective Action: Modify your report routine so that the RIGHT MARGINspecification is a column between the current column and the report margin,and recompile.

-4647 Description of Error: Cannot open file filename to read a TEXT variable value.

Corrective Action: An I/O error occurred while trying to read the tempo-rary file in which the TEXT or BYTE variable is stored. This can be caused byinsufficient space on the disk, or by file corruption.

-4648 Description of Error: I/O error while running fglc.

Corrective Action: Check space availability on your disk. When enoughspace has been made available, rerun fglc.

-9143 Description of Error: Character, Text, and Byte data cannot be printed with"using" formats.

Corrective Action: Be sure you have not attempted to use the USING key-word with Character, Text, and Byte data. You can only use it with date andnumber data.

1203 Description of Error: Cannot find message file. Check INFORMIXDIR andDBLANG.

Corrective Action: INFORMIX-4GL cannot locate a needed message file.Check that both the INFORMIXDIR and DBLANG environment variables areset with the appropriate pathname. Contact your System Administrator ifyou need help with this action.

1204 Description of Error: Type of terminal is unknown to the system.

Corrective Action: Check the setting of the TERM environment variable.Check to see that your TERMCAP or TERMINFO environment variables havebeen set to the correct files. TERMCAP is usually set to /etc/termcap or$INFORMIXDIR/etc/termcap, TERMINFO is usually set to /usr/lib/terminfoor $INFORMIXDIR/lib/terminfo. Contact your System Administrator ifyou need help with this action.

1310 Description of Error: Program error at module-name, line number line-num-ber.

Corrective Action: A statement in the indicated line cannot be executed(possibly because of an error or omission earlier in your program).

118 Error Messages

Page 933: Manual Informix

1354 Description of Error: <byte value>

Corrective Action: This contains a binary large object (BLOB) of type BYTE.

2002 Description of Error: You have entered the wrong number of parameters.The call format is as follows:

form4gl -d form-name database-name table1 table2 ...

Corrective Action: Check the sequence of parameters present on thecommand line.

2005 Description of Error: Database database-name not found or not correctformat.

Corrective Action: Check that the DBPATH environment variable includesthe full pathname of the directory holding the database. Contact your SystemAdministrator if you need help with this action.

2008 Description of Error: The table table-name does not exist in the database.

Corrective Action: The table name included in the TABLE section of the formspecification file is not found in the database specified in the DATABASE sec-tion. Check the spelling of the table name.

2009 Description of Error: You have not selected any database tables.

Corrective Action: You must include one or more table names in the TABLESsection of the form specification file.

2010 Description of Error: There is not enough memory to use the default formoption for this particular choice of tables.

Corrective Action: You have exceeded the data space limits of yourmachine. Reduce the number of tables included in the form.

2011 Description of Error: Default FORM4GL has run out of memory.

Corrective Action: You have exceeded the data space limits of yourmachine. Reduce the number of tables included in the form. Recompile theform specification.

2012 Description of Error: Form output table form-name could not be opened.

Corrective Action: You may have exceeded the open file limit of 14 data files(this number includes the output file). Reduce the number of tables includedin the form. Recompile the form specification.

Error Messages 119

Page 934: Manual Informix

2017 Description of Error: The default form has exceeded its label limit.

Corrective Action: A form can use up to 26 one-character fields, 260 two-character fields, and 1000 fields of three characters or more. Reduce the num-ber of tables in the default form. Recompile the form specification.

2018 Description of Error: The default form has exceeded its limit of 260 two-character labels.

Corrective Action: The total number of two-character fields contained in thetables used to generate the default form exceeds the 260 limit. You mustdelete one or more of the tables containing two-character fields. Recompilethe form specification.

2019 Description of Error: The default form has exceeded its limit of 26 one-char-acter labels.

Corrective Action: The total number of one-character fields contained in thetables used to generate the default form exceeds the 26 limit. You must deleteone or more of the tables containing one-character fields. Recompile the formspecification.

2020 Description of Error: The following tables are involved: table-name.

Corrective Action: The indicated tables are involved in the specifiederror(s).

2028 Description of Error: The form compilation found warnings and no errors.

Corrective Action: You can use the form, but check the specified file to checkthe warnings.

4150 Description of Error: Program error at module-name, line number line-num-ber.

Corrective Action: A statement in the indicated line cannot be executed(possibly because of an error or omission earlier in your program).

4152 Description of Error: FORMS statement error number error-number.

Corrective Action: Something is wrong with the input, display, or data typeconversion that your program specifies. Refer to the corresponding errornumber in this manual. (This error can occur with statements that do not usescreen forms.)

4153 Description of Error: SQL statement error number error-number.

Corrective Action: Refer to the corresponding error number in this manual.

120 Error Messages

Page 935: Manual Informix

4154 Description of Error: Program stopped at module-name, line numberline-number.

Corrective Action: Look for additional messages to see why executionstopped.

4155 Description of Error: 4GL run-time error number error-number.

Corrective Action: Refer to the corresponding error number in this manual.

4156 Description of Error: ISAM error number error-number.

Corrective Action: Refer to the corresponding error number in this manual.

Error Messages 121

Page 936: Manual Informix

122 Error Messages

Page 937: Manual Informix

Index

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Index

Aa command-line option 1-62A symbol in PICTURE format

strings 4-38ABSOLUTE keyword, FETCH

statement 3-17, 7-98Accept key 7-166ACCEPT KEY keywords, OPTIONS

statement 7-79, 7-166Access privileges 3-41

ALL 7-115, 7-187ALTER 7-16, 7-115, 7-187CONNECT 3-41, 7-52, 7-116,

7-187, E-23database privileges 7-42, 7-116DBA 3-41, 7-116, 7-187default 3-41DELETE 7-115, 7-187for a synonym 7-47for database administrator 3-41FROM PUBLIC 7-188INDEX 7-115, 7-187INSERT 7-115, 7-187, E-14removing 7-187RESOURCE 3-41, 7-116, 7-187SELECT 7-115, 7-187, 7-204table privileges 3-41, 7-115TO PUBLIC 3-41, 7-116UNIX permissions 7-42UPDATE 7-115, 7-187view privileges 3-60, 7-117

ACTION Menu (upscolutility) E-38

Active set of a query 2-22, 3-14ADD keyword, ALTER TABLE

statement 7-14

AFTER DELETE clauseINPUT ARRAY 7-133

AFTER FIELD clauseINPUT ARRAY statement 7-132

AFTER GROUP OF controlblock 2-48, 5-25

AFTER keywordINPUT ARRAY statement 7-130INPUT statement 7-123REPORT statement 5-25

Aggregate functionAVG 5-46, 7-249COUNT 5-46, 7-249GROUP 5-46, 7-223in a query 5-46, 7-223, 7-240, 7-249in a report 2-47, 5-26, 5-44MAX 5-46, 7-249MIN 5-46, 7-249PERCENT 5-46SUM 5-46, 7-249with ALL 7-249with DISTINCT or

UNIQUE 7-250with NULL values 3-55, 5-46,

7-250Alias of a table

in a form specification file 4-14,4-60, 7-35

in a SELECT statement 7-226,7-235

ALL keywordaggregate functions 7-249dbschema utility E-22GRANT statement 7-115REVOKE statement 7-187SELECT statement 7-222, 7-237with UNION operator 7-246

Page 938: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

ALTER INDEX statement 3-12,7-12

ALTER keywordGRANT statement 7-115REVOKE statement 7-187

ALTER TABLE statement 7-14Ampersand (&) symbol 2-44AND keyword

Boolean operator 2-13, 3-55COLOR attribute 4-25WHERE clause 7-234with BETWEEN 4-25, 7-230

Angle ( < ) brackets 4-42ansi

option of c4gl command 1-33, 7-7option of fglpc command 1-62,

7-7warning message 3-6, 7-7, 7-65

ANSI standards for SQLcompatibility with 7-7

ANY keyword, SELECTstatement 7-237

Application program,compiling 1-27, 1-32, 1-56, 1-61,7-7

Argumentsfor 4GL program command

line 6-5, 6-17for a 4GL function 7-19, 7-110for a 4GL report 5-6passed to a C function 2-55, 7-19,

F-1arg_val function 6-4Arithmetic operators

in a SELECT clause 7-219, J-9in expressions 2-11, 2-36, 4-25

Arraydisplaying 7-79, 7-192of records 4-55, 6-7program array 2-10, 6-6, 7-71,

7-79screen array 4-55, 7-79, 7-192

ARRAY data type 2-10, 5-8, 7-79ARRAY keyword

DEFINE statement 7-71DISPLAY ARRAY statement 7-79INPUT ARRAY statement 7-129

Arrow keys I-4

arr_count function 6-6examples 7-135

arr_curr function 6-7examples 7-135

AS keywordCREATE VIEW statement 7-57GRANT statement 7-116, E-23

ASC keywordCREATE INDEX statement 7-44ORDER BY clause 3-56, 7-243

ASCII characterscollating sequence 4-35, H-2from integer codes 2-25, H-2

ASCII filescolornames I-18form specifications 4-3input data 7-143, E-11output from UNLOAD 7-144,

7-203.4gl source files 1-27, 1-56

ASCII function 2-25Assignment statements 7-5

attributes of display fields 4-16INITIALIZE 2-17, 7-120LET 2-17, 7-142

Asterisk (*) notationarithmetic operator 2-11, 7-219for all columns 2-15, 7-36for all fields 4-54, 7-36for record elements 2-15, 4-55,

7-111in a REPORT routine 5-6in a SELECT clause 7-222in a USING format string 2-44screen field overflow 2-46, 4-11,

7-76searching for * 7-33, 7-233wildcard 7-34, 7-232with the COUNT keyword 3-55,

5-46, 7-249with the PERCENT keyword 5-46

AT keywordDISPLAY statement 7-75OPEN WINDOW

statement 7-160At ( @ ) sign 2-14, 3-7, 7-223

ATTRIBUTE keywordCONSTRUCT statement 7-32DISPLAY ARRAY

statement 4-59, 7-79DISPLAY FORM statement 7-83DISPLAY statement 4-59, 7-75ERROR statement 7-92INPUT ARRAY statement 7-135INPUT statement 7-123, 7-129MESSAGE statement 7-154OPEN WINDOW

statement 7-160OPTIONS statement 7-168PROMPT statement 7-173

Attribute typesAUTONEXT 4-23, 4-57BLINK 4-26, 4-59, 7-77, I-9, I-27BOLD 4-59, 7-163, I-27BORDER 7-163, I-6, I-24COLOR 4-25, 4-63, E-40COMMENTS 4-27, 4-57DEFAULT 4-19, 4-29, 4-57, 7-121,

E-39DIM 4-59, 7-77, 7-163, I-27DISPLAY LIKE 4-15, 4-31DOWNSHIFT 4-32, E-39FORMAT 4-33, E-41INCLUDE 4-19, 4-35, 4-57, 7-212,

E-39INVISIBLE 4-59, 7-77, 7-163, I-27LEFT 4-26, E-41NOENTRY 4-37NORMAL 4-59, 7-154, 7-163PICTURE 4-38, 4-57REQUIRED 4-40REVERSE 4-26, 4-42, 4-59, 7-163,

I-4, I-9, I-27SHIFT 4-57, E-39UNDERLINE 4-26, 4-59, I-9, I-27UPSHIFT 4-43, E-39VALIDATE LIKE 4-15, 4-45VERIFY 4-46, 4-57WORDWRAP 4-21, 4-47

ATTRIBUTES section of formspecification

assigning attributes 4-16assigning field names 4-16default values 4-56, 7-168, E-39definition of 4-16

2 Index

Page 939: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

field tags 4-17, 4-25fields linked to columns 4-15,

4-17for a multiple table form 4-6for multiple-column fields 4-21for multiple-line fields 4-20format 4-16, 4-22form-only fields 4-16, 4-18input and display 4-22, 7-167table of attributes 4-22, 4-26

AUDIT keywordCREATE AUDIT statement 3-46,

7-39DROP AUDIT statement 3-46,

7-85Audit trails 3-45

compared to transactions 3-45CREATE AUDIT 3-45, 7-39DROP AUDIT 3-45, 7-85RECOVER TABLE 3-46, 7-179

AUTOINDEX PATH accessmethod 7-194

Auto-indexing 3-52AUTONEXT attribute 4-23, 4-57,

E-39AVG aggregate function 5-46,

7-249

BBackup copy of a database 3-45,

3-46bcheck utility E-2BEFORE FIELD clause

INPUT ARRAY statement 7-132BEFORE GROUP OF control block

definition of 5-27guidelines for using 5-27

BEFORE keywordALTER TABLE statement 7-14INPUT ARRAY statement 7-130INPUT statement 7-123REPORT statement 5-27

BEGIN WORK statementexplicit transactions 3-44syntax and notes 7-18

Bell of a terminal, ringing 2-19,2-25, 4-38, 7-92

BETWEEN keyword 3-65, 4-25,4-58, 7-229

Binding to database andforms 2-14, 4-17

BLACK attribute 4-26, 4-59, 7-77,I-19

Blank charactersDAY and HOUR separator 2-6,

J-5, J-8default character value 4-7, 4-29in input files 7-144, E-12in WORDWRAP fields 4-48with CLIPPED operator 2-27with FORMAT attribute 4-33with SPACE or SPACES 5-50

BLINK attribute 4-26, 4-59, I-9, I-27BLOB data Intro-7BLUE attribute 4-26, 4-59, 7-77, I-19BOLD attribute 4-59, 7-77, I-27Boolean capabilities I-3, I-21Boolean expression 2-13

examples 4-58, 7-230in syscolatt 4-58, E-41with CASE 7-22with COLOR attribute 4-25, 4-63with CONSTRUCT 7-33with IF 7-118with NULL values 3-55, 4-25with WHERE 7-218, 7-228with WHILE 7-216

Bordered windowgraphics characters used 4-13,

7-163, I-24how displayed on screen 7-163position on screen 7-160

BOTTOM MARGINstatement 5-16, 5-36

Bourne shell C-2Braces ( { } ) symbols

comment indicator 2-3, E-15page layout of form

specification 4-9syntax convention Intro-10

Brackets ( [ ] ) symbolspage layout of form

specification 4-9pattern matching 7-233syntax convention Intro-9

to specify array elements 2-10to specify substrings 2-12, 4-18

Built-in functions 2-24, 5-44BY keyword

CONSTRUCT statement 7-32FORM4GL form specification

file 4-8GROUP BY clause 7-240INPUT statement 2-14ORDER BY clause 3-18, 7-243REPORT statement 5-18, 7-184SCROLL statement 7-192

BY NAME keywordsCONSTRUCT statement 7-32DISPLAY statement 7-75INPUT statement 2-14, 7-122

BYTE data type Intro-7B+ trees E-3

CC Compiler version of 4GL Intro-3,

1-5, 1-7C compiler, function 1-32C functions 1-66, 2-55, 7-19C language functions in 4GL

programs 1-32, 1-64, 2-55C shell C-2c4gl command 1-6, 1-32, 7-7CALL keyword, WHENEVER

statement 7-213CALL statement 2-18

passing parameters with 7-111RETURNING clause 2-56, 7-19syntax and notes 7-19with C functions 1-70, 2-58, 7-19with library functions 6-3

Calling convention for Cfunctions 2-55

CASE statement 2-19EXIT CASE 7-96syntax and notes 7-21

cat utility 1-64, 3-45cfglgo command 1-66, 1-69CHAR data type

acceptable values 3-8, 7-50CHARACTER synonym 2-8, 3-8subscripts 4-18, 4-19, 7-220

Index 3

Page 940: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

with database columns 3-8, 7-50with display fields 4-38, 4-47with variables 2-8, 7-71

CHAR keyword, PROMPTstatement 7-173

CHARACTER data type 2-8, 3-8Character position 2-8, 4-18, E-13C-ISAM (indexed sequential access

method) Intro-4, 3-50CLEAR statement 2-19

syntax and notes 7-23WINDOW 7-60

CLIPPED keyword 2-12in a string expression 2-38, 5-40syntax and notes 2-27with DISPLAY 7-76

CLOSE DATABASE statementdefinition of 3-11syntax and notes 7-27

CLOSE FORM statementclosing an opened form 2-20,

7-159syntax and notes 7-28

CLOSE statementand the FREE statement 7-109and the SQLCA record 3-28syntax and notes 7-25with a SELECT cursor 3-17, 7-25with an INSERT cursor 3-26, 7-25

CLOSE WINDOW statement 2-20syntax and notes 7-30

CLUSTER keywordALTER INDEX statement 3-53,

7-12CREATE INDEX statement 3-53,

7-44Colon ( : ) symbol

as statement label prefix 7-213delimiter in DATETIME

values 2-6, 7-34, E-12, J-5, J-8delimiter in INTERVAL

values 2-6, 7-34, E-12field specification separator E-14,

I-4LABEL statement 7-141ranges with CONSTRUCT 7-34WHENEVER statement 7-213

COLOR attribute 4-25, 4-63, I-19colornames file 4-59, E-40, I-9, I-18

Columnadding 7-14changing column values 3-17,

7-206changing data type 7-14constraints 7-16, 7-53designated as NOT NULL 7-51determining length 7-52indexed 3-50, 7-44joining 7-234, G-1naming conventions 3-6, 7-51NULL value in 3-54removing 7-14renaming 7-181virtual 3-59, 7-58

Column data typesCHAR 2-8, 7-50DATE 2-9, 7-51, C-3DATETIME 2-9, 7-52, J-1DECIMAL 2-7, 7-50, F-1FLOAT 2-8, 7-50INTEGER 2-7, 7-50INTERVAL 2-9, 7-52, J-1MONEY 2-8, 7-50, C-5SERIAL 7-51, 7-139SMALLFLOAT 2-8, 7-50SMALLINT 2-7, 7-50

COLUMN keyword 2-29, 7-181Columns

in stores database tables A-2in system catalogs B-1in upscol tables 4-56, E-37

COLUMNS keyword, OPENWINDOW statement 7-160

Comma ( , ) symbolconcatenation operator 2-12,

7-172in USING format strings 2-44separator in lists 2-15, I-21

COMMAND clauseMENU statement 7-149

Command filedbexport E-7dbload E-12dbschema E-22

Command linearguments of a 4GL program 6-5,

6-17to compile a message file E-28

to compile a screen form 4-9, 4-62to create a customized

runner 1-69, 1-71to invoke a 4GL program 1-6,

1-31, 1-64, 1-65, 1-72, 6-5, 6-17to invoke compiler 1-6, 1-32, 1-61

Comment indicators 2-3, 4-10, I-3,I-21

Comment line 7-162, E-39COMMENT LINE keywords

OPEN WINDOWstatement 7-161

OPTIONS statement 7-165COMMENTS attribute 4-27, 4-57,

7-35, E-39COMMIT WORK statement 3-42

ending transactions 3-23, 3-44syntax and notes 7-31

COMPILE Menu 1-27, 1-56Compile option

FORM Menu 1-17, 1-47, 4-61MODULE Menu 1-12, 1-41PROGRAM Menu 1-22, 1-51

Compile-time errors 1-11, 1-40,4-61, 7-7

Compilingcommand line 1-31, 1-32, 1-61help messages E-27in Programmers

Environment 1-10, 1-31, 1-39,1-61

programs that call Cfunctions 1-65

screen forms 1-15, 1-45, 4-60with ansi flag 1-32, 1-62, 3-6, 7-7

Composite column list 7-16, 7-53COMPRESS keyword,

WORDWRAP attribute 4-48Concatenation operator 2-12, 7-172Concurrency control 3-42, 7-99Conditional statements

CASE 2-19, 7-21COLOR attribute 4-25, 4-63IF 2-19, 3-22, 7-118syscolatt file 4-58, E-41WHILE 7-216

CONNECT access privilege 3-41,7-116, E-22

4 Index

Page 941: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

CONNECT keywordGRANT statement 7-116REVOKE statement 7-187

Constantdate-time 2-12, J-1floating number 2-5integer 2-5string 2-5

CONSTRAINT keywordALTER TABLE statement 7-14CREATE TABLE statement 7-49

Constraints 7-139changing 3-11, 7-16creating 3-11, 7-53names 3-7, 7-16, 7-53owner 3-7, 7-16

CONSTRUCT statement 2-20NOENTRY fields 4-37symbols recognized 7-33syntax and notes 7-32wildcard characters 7-34

CONTINUE keyword,WHENEVER statement 2-21,2-22, 7-213

CONTINUE statement 2-19FOR 7-105FOREACH 7-107MENU 7-152syntax and notes 7-38WHILE 7-216

Control blocks 5-23COUNT aggregate function 3-55,

5-46, 7-249CPU cost for a query 3-63, 7-194CREATE AUDIT statement 3-45,

7-39CREATE DATABASE

statement 3-11current database 7-41syntax and notes 7-41system catalogs 7-41WITH LOG IN 3-43, 7-42

CREATE INDEX statement 3-12syntax and notes 7-44with ASC 7-16, 7-44, 7-53with DESC 7-44with UNIQUE and

DISTINCT 7-44

CREATE SYNONYMstatement 3-11, 7-47

CREATE TABLE statement 3-11assigning data types J-3guidelines for using 7-49NOT NULL clause 3-54, 7-51notes 7-51owner naming 7-51syntax 7-49TEMP keyword 3-58, 7-51UNIQUE keyword 7-53WITH NO LOG 7-50

CREATE VIEW statement 3-58guidelines for using 7-57owner naming 7-57syntax and notes 7-57WITH CHECK OPTION 3-60,

7-58Currency symbol

default ( = $ ) 2-8, 4-29, C-5in dbload input files E-12in format strings 2-47

Current database 3-11CLOSE DATABASE

statement 7-27closing 3-11, 7-27creating 3-11, 7-41DATABASE statement 7-62FETCH statement 7-99selecting 3-11, 7-62

CURRENT function 3-65, 7-258CURRENT keyword

CURRENT function 2-30, 3-65DEFAULT attribute 4-30DELETE statement 3-18, 7-73FETCH statement 7-98for a DATETIME value J-13UPDATE statement 3-19, 7-207

CURRENT OF keywordsDELETE statement 3-18, 7-73UPDATE statement 3-19, 7-207

Current option of a menu 1-8, 1-37Current row of a query 3-14, 3-18Current window 7-23, 7-60, 7-161CURRENT WINDOW

statement 2-20syntax and notes 7-60

Cursor 3-13advancing 3-17, 7-98closing 3-18, 7-25declaring 3-14, 7-64FOR UPDATE 3-17, 7-99, 7-157non-SCROLLing 3-14opening 3-17, 7-156position 3-19, 3-20scope of reference 2-5, 3-15, 7-67SCROLL 3-14, 7-65with CLOSE 3-16, 7-25with DELETE 3-18with FETCH 3-16, 7-99with FOREACH 3-16with FREE 3-40, 7-109WITH HOLD 3-14, 3-25, 7-26,

7-65, 7-157with INSERT 3-25, 7-9, 7-26, 7-65with OPEN 3-16, 7-156with SELECT 3-13, 7-64, 7-220with UPDATE 3-17, 7-99, 7-207

CURSOR keywordDECLARE statement 3-14

Cursor movement I-22as determined by FETCH 3-17as determined by INPUT 7-125in a menu 7-150in a screen array 7-80in a screen form 4-23, 7-35in a screen record 4-16

Cursor WITH HOLDBEGIN WORK statement 3-25COMMIT WORK statement 3-25DECLARE statement 3-24, 7-65FETCH statement 3-24OPEN statement 7-157

customer table in storesdatabase Intro-11, A-2

Customized runners 1-50, 1-66CYAN attribute 4-26, 4-59, 7-77,

I-19

DData access statements 7-6

GRANT 3-40LOCK TABLE 3-40REVOKE 3-40UNLOCK TABLE 3-40

Index 5

Page 942: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Data conversionin an INSERT statement 7-140in an UPDATE statement 7-208in expressions 2-10, 2-36

Data definition statements 7-6ALTER INDEX 3-12ALTER TABLE 3-11CLOSE DATABASE 3-11CREATE DATABASE 3-11CREATE INDEX 3-12CREATE SYNONYM 3-11CREATE TABLE 3-11CREATE VIEW 3-11DATABASE 3-11DROP DATABASE 3-11DROP INDEX 3-12DROP SYNONYM 3-12DROP TABLE 3-11DROP VIEW 3-11RENAME COLUMN 3-12RENAME TABLE 3-11UPDATE STATISTICS 3-12

Data fields E-12Data integrity statements 3-42, 7-6Data manipulation statements 7-6

DELETE 3-12, 7-73INSERT 3-12, 7-138LOAD 3-12, 7-143SELECT 3-12, 7-193, 7-218UNLOAD 3-12, 7-203UPDATE 3-12, 7-206

Data typebinary large objects

(BLOB) Intro-7C language 2-55, F-2changing 7-14conversion 2-10, 2-36, 7-140date-time data types J-1floating decimal point 2-8, 3-9of columns in a table 3-8, 7-49of variables 5-7, 7-71, 7-120of view columns 7-58storage requirements 7-52synonyms 2-7

Data typesARRAY 2-10, 5-8BYTE Intro-7CHAR 2-8, 3-8, 4-29, 5-40, 7-50,

E-14

CHARACTER 2-8, 3-8DATE 2-9, 3-9, 4-29, 5-40, 7-51,

C-3, E-12, J-10DATETIME 2-9, 3-10, 4-30, 5-40,

E-12, J-2DEC 2-8, 3-9DECIMAL 2-7, 2-10, 3-9, 4-33,

7-50, F-1DOUBLE PRECISION 2-8, 3-9FLOAT 2-8, 3-9, 4-33INT 2-7, 3-8INTEGER 2-7, 3-8, 7-50INTERVAL 2-9, 3-10, 4-30, 5-40,

E-12, J-5LIKE specification 2-9, 5-7MONEY 2-8, 3-9, 4-29, 5-40, 7-50,

C-5, E-12NUMERIC 2-8, 3-9REAL 2-8, 3-9RECORD 2-9, 5-7SERIAL 2-9, 3-9, 4-37, 5-40, 7-51,

7-139SMALLFLOAT 2-8, 3-9SMALLINT 2-7, 3-8TEXT Intro-7VARCHAR Intro-7

Data validationupscol utility 4-56, E-39using views 3-60VALIDATE LIKE attribute 4-45VALIDATE statement 2-24, 7-211

Databaseaccess privileges 3-41closing 7-27creating 3-64, 7-41creating tables 3-11, 7-49creating views 3-58, 7-57data manipulation

statements 3-12database subdirectory 3-5, 7-41granting user access 3-41, 7-115indexes 3-50map of stores A-5naming conventions 3-6, 7-41owner naming and MODE

ANSI 3-7recovering Intro-7, 3-45relational 3-5remote 7-35

removing 3-11, 7-86removing indexes 3-12, 7-88removing tables 3-11, 7-90renaming tables 3-11, 7-182replication with dbschema E-22revoking user access 3-41, 7-187stores demonstration A-1system catalogs 3-5, B-1tables in 3-5, 7-49with a transaction log 3-42

Database administrator (DBA)access privileges 1-18, 3-41,7-116

Database conversionwith dbupdate utility E-25with sqlconv utility E-31

Database engines Intro-6DATABASE section of form

specificationcreating as FORMONLY 4-7definition of 4-7format 4-6WITHOUT NULL INPUT 4-7,

4-29DATABASE statement 2-22

definition of 3-11, 7-62EXCLUSIVE 7-63syntax and notes 7-62

DATE data typeacceptable values 2-46, 7-51data conversion J-16in dbload input files E-12manipulating arithmetically J-10with database columns 3-9with display fields 2-46, 2-47,

4-29, 4-33, 7-52, C-3with variables 2-9, 7-71

DATE keywordCREATE TABLE statement 7-51DATE function 2-32DATE() function 2-33, 7-9, 7-252

DATETIME data type 2-9, J-2acceptable values 7-51, J-2entered as a character string J-8entered as a literal value 4-30, J-3in dbload input files E-12manipulating arithmetically 2-36,

J-9

6 Index

Page 943: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

using the CURRENTkeyword J-13

with database columns 3-10with display fields 4-30with variables 2-9, 7-71, J-16

Date-time expression 2-12, 7-248DAY keyword

DATETIME qualifier 3-10, J-2DAY( ) function 2-34, 7-9, 7-253INTERVAL qualifier 3-10, J-12

DBA access privilege 3-7, 3-41,7-16, 7-85, E-6, E-23

DBA keywordGRANT statement 7-116REVOKE statement 7-187

DBA (DatabaseAdministrator) 3-40, 3-45

DBANSIWARN environmentvariable 3-6, 3-25, 3-64, 7-7, C-2

DBDATE environmentvariable C-3

DBDELIMITER environmentvariable 7-144, 7-203, C-3, E-12

DBEDIT environmentvariable 1-12, 1-26, 1-41, 1-55,C-4

dbexport utility E-6DBLANG environment

variable C-4, E-30dbload utility E-11, E-33DBMONEY environment

variable C-5DBPATH environment

variable 1-18, 1-29, 1-58, C-6,E-23

DBPRINT environmentvariable 5-10, C-6

dbschema utility E-22DBTEMP environment

variable C-6dbupdate utility 3-54, E-25Deadlock 7-197Debug option

MODULE Menu 1-42PROGRAM Menu 1-53

Debugger, Interactive Intro-4, 1-38,1-53, 1-65

Debugger, invoking 1-59, 1-61DEC data type 2-8, 3-9

DECIMAL data typeacceptable values 2-7, 3-9, 7-50DEC synonym 2-8, 3-9floating decimal point in 2-7,

2-44, 3-9NUMERIC synonym 2-8, 3-9scale and precision 2-7, 2-10, 2-11with database columns 3-9with display fields 2-44, 4-33with variables 2-7, 7-71, F-1

DECIMAL functions for C F-1DECLARE statement

and SQLCA record 3-63assigning a cursor 3-14, 3-29DELETE operations 3-25FOR UPDATE 3-19, 7-66, 7-74guidelines for using 3-35INSERT cursor 3-26, 3-37, 7-139SCROLL option 3-20, 7-65SELECT cursor 3-14, 3-35syntax and notes 7-64WITH HOLD option 3-23, 7-65

DEFAULT attribute 4-29, 4-57CURRENT 4-30TODAY 4-30with INITIALIZE statement 4-58,

7-121with WITHOUT

DEFAULTS 4-29, 7-124with WITHOUT NULL

INPUT 4-29Default editor 1-26, 1-55, C-4Default form specification file

creating at system prompt 4-62generating 1-16, 1-46, 4-61modifying 1-16, 1-46, 4-61

Default screen attributes 4-56,7-168

Default screen record 4-55DEFER statement

forms of 2-23global flags set 2-23, 7-69INTERRUPT 2-23syntax and notes 7-69

DEFINE statementdefining a program array 2-10defining a record 2-9, 7-72defining global variables 2-4,

7-112

defining variables 2-4, 2-7, 7-71in a function 2-4, 7-110in a report 2-4, 5-7, 7-184LIKE keyword 2-9, 7-71location 2-4scope of variables 2-17syntax and notes 7-71

Defining global variables 2-4, 7-112Delete key 7-166, I-5, I-23DELETE keyword

GRANT statement 7-115INPUT ARRAY statement 7-130OPTIONS statement 7-166REVOKE statement 7-187

DELETE statement 3-12DATETIME or INTERVAL

values J-15examples 3-33functions in 7-248syntax and notes 7-73WHERE CURRENT OF

clause 3-18, 3-19DELIMITER keyword

dbload command file E-12LOAD statement 7-143UNLOAD statement 7-203

Delimiters in a screen form 4-11changing 4-52

DELIMITERS statement 4-52Demonstration application,

listing A-15Demonstration database A-1

description of Intro-11, A-1restoring 1-6

DESC keywordCREATE INDEX statement 7-44ORDER BY clause 3-56, 7-243

DIM attribute 4-59, 7-77, I-8Direct memory access

(DMA) Intro-4DISPLAY ARRAY statement 2-20

arr_curr function 6-7EXIT DISPLAY 7-96set_count function 6-20syntax and notes 7-79

DISPLAY ATTRIBUTEkeywords 7-168

Index 7

Page 944: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Display field 4-10default field widths 4-11determining field widths 4-11dividing long CHAR

columns 4-18, 4-19field names 4-11, 4-16, 4-22field tag 4-10, 4-25, 4-63format of 2-44, 4-10form-only field 4-16, 4-18guidelines for using 4-11labels for 4-12multiple-column 4-21, 4-34, 4-42multiple-line fields 4-11, 4-47screen arrays 4-11, 4-54, 7-79specifying search criteria 7-32verifying field widths 4-12

DISPLAY FORM statement 2-20syntax and notes 7-83

DISPLAY LIKE attribute 4-15, 4-31DISPLAY statement 2-20

AT 2-27BY NAME 7-76CLIPPED 2-27EXIT DISPLAY 7-96formatting 2-46syntax and notes 7-75TO 2-15

DISTINCT keywordaggregate functions 3-55, 7-249ALTER TABLE statement 7-16CREATE INDEX statement 7-44CREATE TABLE statement 7-53SELECT statement 7-222

Distributed query acrossdatabases Intro-7

Documentation Intro-3DOUBLE PRECISION data

type 2-8, 3-9DOWN keyword

SCROLL statement 7-192syscolval table 4-57, E-39

DOWNSHIFT attribute 4-32, 7-35,E-39

downshift function 6-9DROP AUDIT statement 3-45, 7-85DROP DATABASE statement 3-11

syntax and notes 7-86DROP INDEX statement 3-12

syntax and notes 7-88

DROP keyword, ALTER TABLEstatement 7-14

Drop option, PROGRAMMenu 1-24

DROP SYNONYM statement 3-12,7-89

DROP TABLE statement 3-11syntax and notes 7-90

DROP VIEW statement 3-58syntax and notes 7-91

Dynamic managementstatements 7-6

DECLARE 3-29EXECUTE 3-28FREE 3-29PREPARE 3-28

EEBCDIC conversion of ASCII

strings 2-58Editor blanks (in multiple-line

fields) 4-48Ellipsis ( . . . ) symbols 7-150

syntax convention Intro-11ELSE keyword, IF statement 7-118END keyword

CASE statement 2-19, 7-21DEFINE statement 7-71DISPLAY ARRAY statement 7-79FOR statement 7-104FOREACH statement 7-106FORM4GL form specification

file 4-10FUNCTION statement 7-110GLOBALS statement 7-112IF statement 7-118INPUT ARRAY statement 7-130MAIN program block 7-148MENU statement 7-150PROMPT statement 7-174REPORT statement 5-20, 7-184WHILE statement 3-27, 7-216

Environment variableDBANSIWARN 3-6, 3-64, 7-7, C-2DBDATE C-3DBDELIMITER 7-144, 7-203, C-3

DBEDIT 1-12, 1-15, 1-26, 1-41,1-45, 1-55, 4-61, C-4

DBLANG C-4, E-30DBMONEY C-5DBPATH 1-18, 1-29, 1-58, 7-62,

C-6DBPRINT 5-10, C-6DBTEMP C-6INFORMIXDIR C-7, E-30INFORMIXTERM C-7, I-1, I-20SQLEXEC C-7TERMINFO I-20, I-25

Equal ( = ) sign 2-13, 4-16, 7-33Error handling

4GL library functions 6-10built-in functions 2-22compile-time errors 1-11, 1-40,

4-63creating an error log 6-23displaying error messages 6-11,

7-92errorlog function 6-13exception handling 2-23, 7-69Interrupt key 2-21, 7-69logging programmer-defined

error messages 6-13overview of 2-21run-time errors 1-65, 2-21, 6-23SQLCA global record 2-22, 3-63startlog function 6-23trapping errors 2-22, 7-214trapping interrupts 2-23, 7-69trapping warnings 2-22, 7-213WHENEVER statement 2-22with status variable 2-22, 6-10

ERROR keywordERROR statement 7-92OPTIONS statement 7-165WHENEVER statement 7-213

Error lineerr_print function 6-11err_quit function 6-12location 7-167

Error log file 6-13, 6-23, E-11Error messages 1-35, 6-10, 6-12,

6-23editing the 4glusr.msg file E-29

Error record 6-23ERROR statement 2-19, 7-92

8 Index

Page 945: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

errorlog function 2-23, 6-13err_get function 2-23, 6-10err_print function 2-23, 6-11err_quit function 2-23, 6-12Escape key 7-167ESCAPE keyword, WHERE

clause 7-231, 7-232ESQL/C

functions 1-32, 1-64language Intro-4

EVERY ROW keywordsdefault FORMAT section of a

report 5-20ON EVERY ROW control

block 5-31EXCLUSIVE keyword

DATABASE statement 7-62LOCK TABLE statement 3-49,

7-146Exclusive mode, opening the

database 3-45, 7-200, E-6EXECUTE statement 3-28

guidelines for using 3-33syntax and notes 7-94USING 3-33

EXISTS keyword, SELECTstatement 7-238

Exit optionFORM Menu 1-18, 1-47MODULE Menu 1-14, 1-43PROGRAM Menu 1-24, 1-53

EXIT statement 2-19CASE 7-21DISPLAY 7-79FOR 7-105FOREACH 7-107INPUT ARRAY 7-130MENU 3-23, 7-150PROGRAM 7-97syntax and notes 7-96WHILE 7-216

Expression 2-11Boolean 2-13, 3-55, 7-21data conversion 2-10, J-11date-time 2-12, 2-36, J-1, J-11in a report 5-44in a SELECT statement 7-219NULL values 3-54

number 2-11, 2-44string 2-12using in statements 2-13

EXTEND function 2-35, 7-260, J-11EXTERNAL keyword

REPORT statement 5-18, 7-184

FFALSE (Boolean constant) 2-5, 3-55FETCH statement

default condition 7-99examples 3-36guidelines for using 3-16NOTFOUND code 3-63, 7-99syntax and notes 7-98with SELECT 3-36, 7-224

fgiusr.c file 1-67fgldb command 1-66fglgo command 1-6, 1-50, 1-64, 6-4fglpc command 1-6, 1-61, 7-7FIELD keyword

INPUT ARRAY statement 7-130INPUT statement 7-123

Field names in screen forms 4-15,4-17, 6-14

Field tag 4-9generated by FORM4GL 4-11in Boolean expressions 4-25, 4-63in the ATTRIBUTES section 4-16in the SCREEN section 4-10, 4-11naming conventions 4-17

Fields of input records 7-143, E-11File extensions

.4be 1-36, 1-73

.4bl 1-35, 1-73

.4bo 1-35, 1-73

.4ge 1-10, 1-13, 1-20, 1-35, A-15

.4gi 1-49, 1-54, 1-56, 1-58, 1-64,1-72

.4gl 1-11, 1-26, 1-32, 1-35, 1-54,1-55, 1-61, 1-72, A-15

.4go 1-50, 1-54, 1-56, 1-61, 1-62,1-64, 1-72

.c 1-21, 1-35, 1-69

.dat 3-5, E-2

.dbs 3-5

.ec 1-21, 1-29, 1-32, 1-35, 1-69

.erc 1-35, 1-72

.err 1-31, 1-35, 1-60, 1-72, 4-12,4-63, 7-7

.exp E-7

.fbm 1-36, 1-73

.frm 1-35, 1-72, 4-61, 4-62, 4-63

.h 1-70, F-1

.idx 3-5, E-2

.msg E-29

.o 1-10, 1-27, 1-35

.out 1-33, 1-69, 7-194, E-6

.pbr 1-36, 1-73

.per 1-15, 1-35, 1-72, 4-63

.sql E-7

.src A-15FILE keyword

dbload command file E-12OPTIONS statement 7-166, E-27

Fill characterampersand 2-44asterisks 2-44dollar sign 2-45parentheses 2-45pound sign 2-44, 4-33table of 2-44

Filters in a query 7-194, G-3FINISH REPORT statement 2-21

guidelines for using 5-33syntax and notes 7-101

FIRST keywordFETCH statement 3-23, 7-98OPEN WINDOW

statement 7-161OPTIONS statement 7-167REPORT statement 5-29

FIRST PAGE HEADER controlblock 5-29, 5-34

Fixed-length records E-12FLOAT data type

acceptable values 3-9, 7-50DOUBLE PRECISION

synonym 2-8, 3-9with database columns 3-9with display fields 4-33with variables 2-8, 7-71

Floating number constant 2-5

Index 9

Page 946: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

FLUSH statementguidelines for using 3-26status variable and SQLCA

record 3-28syntax and notes 7-102

FOR keywordCONTINUE statement 7-38CREATE AUDIT statement 3-46,

7-39CREATE SYNONYM

statement 7-47DECLARE statement 3-25, 7-64DROP AUDIT statement 7-85PROMPT statement 7-173UPDATE STATISTICS

statement 7-210FOR statement 2-18

EXIT FOR 7-96syntax and notes 7-104

FOR UPDATE cursorDECLARE statement 3-17, 7-64DELETE statement 3-18FETCH statement 3-19, 7-99FOREACH statement 3-19OPEN statement 3-48, 7-157row-level locking 3-48

FOREACH statement 2-18CONTINUE FOREACH 7-38examples 3-16EXIT FOREACH 7-96syntax and notes 7-106

Foreground colors 7-168, I-17FORM Design Menu 1-14, 4-61FORM keyword

CLEAR statement 7-23CLOSE FORM statement 7-28OPEN FORM statement 7-159OPEN WINDOW

statement 7-160OPTIONS statement 7-168

FORM LINE keywordsOPEN WINDOW

statement 7-161OPTIONS statement 7-166

Form specification file, sections ofATTRIBUTES 4-4, 4-16, 7-167DATABASE 4-4, 4-7INSTRUCTIONS 4-51

SCREEN 4-4, 4-8TABLES 4-4, 4-14

Form specification file, using 4-3correcting errors 1-16creating 4-62default form specification

file 4-62generating 1-14, 1-43, 4-61graphics characters 4-12identifier 2-5, 7-28, 7-159multiple tables in 4-14, 4-61overview 4-3PERFORM forms 4-63structure 4-4

FORM4GLattribute syntax 4-22command line syntax 4-9, 4-62,

4-63creating a default form

specification file 4-61default display field 4-9default field tags 4-62default screen records 4-54description 4-3file extensions created by 4-63from Programmers

Environment 1-17, 1-46, 4-61graphics characters in screen

section 4-12subscripting a CHAR

column 4-18using defaults in syscolval and

syscolatt 4-17verifying field widths 4-12

FORMAT attribute 4-33guidelines for using 4-33multiple-column fields 4-21

FORMAT section of REPORTstatement

AFTER GROUP OF 5-25aggregate functions 5-46BEFORE GROUP OF 5-27CLIPPED 5-40COLUMN 5-35control blocks 5-23definition of 5-20, 7-184EVERY ROW 5-13, 5-21fill characters 2-44FIRST PAGE HEADER 5-29

LINENO 5-48NEED statement 5-38ON EVERY ROW 5-31ON LAST ROW 5-33PAGE HEADER 5-34PAGE TRAILER 5-36PAGENO 5-49PAUSE statement 5-39PRINT FILE statement 5-42PRINT statement 5-40SKIP statement 5-43SPACE 5-50TIME 2-41USING 5-40WORDWRAP 5-40, 5-51

Format stringswith FORMAT attribute 4-33,

E-41with PICTURE attribute 4-38with USING operator 2-44

Formatting a reportautomatic page numbering 5-35default report format 5-21formatting dates 2-46, C-3formatting numbers 2-44grouping data 5-46page headers and trailers 5-29,

5-34, 5-36printing column headings 5-35setting margins 5-12, 5-13, 5-15,

5-16setting page length 5-17skipping to top of page 5-43starting on a new page 5-38

Formatting numberexpressions 2-44

Form-only field 4-18, 4-19, 4-22FORMONLY keyword

ATTRIBUTES section 4-18DATABASE section 4-7, 4-15INSTRUCTIONS section 4-54

FRACTION keywordDATETIME qualifier 3-10, J-2INTERVAL qualifier 3-10, J-6

FREE statement 3-29, 3-39, 7-109FROM clause

OUTER keyword 3-62, 7-226, G-3SELECT statement 3-62, 7-226table alias 7-235

10 Index

Page 947: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

FROM keywordCONSTRUCT statement 7-32DELETE statement 7-73INPUT ARRAY statement 7-129INPUT statement 7-122LOAD statement 7-143OPEN FORM statement 7-159PREPARE statement 3-30, 7-171PUT statement 7-177REVOKE statement 7-187SELECT statement 3-62

FunctionASCII 2-25CLIPPED 2-27COLUMN 2-29CURRENT 3-65, 4-30, 7-258, J-13DATE 2-32DATE() 2-33, 7-252DAY() 2-34, 7-253EXTEND() 2-35, 7-9, 7-260LENGTH() 2-38, 7-9MDY() 2-39, 7-254MONTH() 2-40, 7-9, 7-255SPACES 5-50TIME 2-41TODAY 2-42, 3-65, 4-30, 7-9USER 3-65WEEKDAY( ) 2-53, 7-9, 7-256WORDWRAP 5-51YEAR( ) 2-54, 7-9, 7-257

Function keys 1-50, I-5, I-23FUNCTION statement

and variables 2-17defining a record in 7-111parameters in 2-17, 7-110RETURN 7-110, 7-186syntax and notes 7-110

Functions 2-174GL library 2-22, 6-3aggregate 3-55, 7-249built-in functions 2-24C language 1-32, 1-64, 2-55, F-1calling a function 7-19, 7-111in an expression 6-3INFORMIX-ESQL/C 1-32, 1-64values returned 2-17, 7-111

GGenerate option, FORM

Menu 1-16, 1-46Global flags 2-23Global Source array 1-50Global variables 2-4GLOBALS statement 2-18

syntax and notes 7-112with DEFINE LIKE 7-112

GO TO or GOTO keywordsWHENEVER statement 7-213

GOTO statementLABEL 2-19, 7-114, 7-141syntax and notes 7-114

GRANT statement 3-40, 7-10CONNECT 3-41DBA 3-41RESOURCE 3-41syntax and notes 7-115table privileges 3-41

Graphics characters in forms 4-12Greater ( > ) than symbol 1-64, 2-13,

E-19relational operator 2-13, 7-33REVERSE attribute 4-42

GREEN attribute 4-26, 4-59, 7-77,I-19

GROUP aggregate functions 5-46GROUP BY clause, SELECT

statementin definition of a view 3-59syntax and notes 7-240with NULL values 3-56

GROUP keywordAFTER GROUP OF control

block 5-25BEFORE GROUP OF control

block 5-27REPORT statement 5-46

HHAVING clause, SELECT

statement 7-242HEADER keyword

FIRST PAGE HEADER controlblock 5-29

PAGE HEADER controlblock 5-34

Help filecalling help messages 7-150,

7-151, 7-166, 7-173compiling with mkmessage E-27designating a Help key 7-166designating a pathname 7-166format of E-27showhelp function 6-21, E-29

HELP keywordINPUT ARRAY statement 7-129INPUT statement 7-123MENU statement 7-149OPTIONS statement 7-166, E-27PROMPT statement 7-173

Help line 7-149, 7-154Help menu 6-21, E-29Help message

creating and compiling 1-9, 1-38,E-27

displaying 1-8, 1-37, 6-22, 7-123,7-129, 7-166

Hidden options of menus 7-152High availability Intro-7HOLD keyword, DECLARE

statement 7-64HOUR keyword

DATETIME qualifier 3-10, J-2INTERVAL qualifier 3-10, J-6

Hyphen ( - ) symbolcomment indicator 2-4delimiter in DATETIME

values E-12delimiter in INTERVAL

values E-12in USING format strings 2-45in window border 4-13, I-6range indicator in dbload

files E-13

Index 11

Page 948: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Ii4gl command 1-6, 1-25, 4-61i4gldemo script Intro-11, 1-6Identifier

defining 3-28, 4-54, 7-71distinction between INFORMIX-

4GL and SQL 3-7naming conventions 2-4, 4-54PREPAREd statements 7-67,

7-109scope of reference 2-4, 7-67, 7-172

IF statement 2-19relationship to CASE 7-22syntax and notes 7-118

Implicit transactions 3-6IN keyword

CREATE AUDIT statement 3-46,7-39

CREATE DATABASEstatement 3-43

CREATE TABLE statement 7-10,7-50

LOCK TABLE statement 3-49,7-146

SELECT statement 7-230START DATABASE

statement 3-43INCLUDE attribute 4-57

definition of 4-35guidelines for using 4-35specifying values in 7-212

Indexascending and descending 7-53auto_indexing 3-52check and repair index files E-2clustered 3-52, 7-12, 7-45creating the index 7-44, E-22filters 3-52, 7-194guidelines for using 3-50multiple-column 7-16, 7-44NULL value 3-54removing from a database 7-88UNIQUE 7-44, 7-53, 7-139with dbload utility E-20

INDEX keywordGRANT statement 7-115REVOKE statement 7-187

INDEX PATH table accessmethod 7-194

Indirect typing of programvariables 7-71

infield functionhelp messages E-29ON KEY 7-126syntax and notes 6-14, 7-134

infocmp utility I-24, I-27informix user name E-6INFORMIX-4GL

as a report writer 5-3as a screen-building utility 4-3command file names 1-31, 1-61language overview 2-3versions Intro-3, 1-5

INFORMIXDIR environmentvariable C-7, E-30

INFORMIX-ESQL/Cfunctions 1-32, 1-64

INFORMIX-OnLine databaseengine Intro-6, 7-6

INFORMIX-SE databaseengine Intro-6, 7-6

INFORMIX-SQL applicationdevelopment tool 4-63

INFORMIX-STAR add-on Intro-7INFORMIXTERM environment

variable C-7, I-1, I-20INITIALIZE statement 2-17, 7-120INPUT ARRAY statement 2-20

arr_curr function 6-7infield function 6-14, 7-134NOENTRY fields 4-37scr_line function 6-18set_count function 6-20syntax and notes 7-129table of functions in 7-135terminating 7-132

INPUT ATTRIBUTE clause ofOPTIONS statement 7-168

Input buffer 3-26, 7-139Input files

dbload utility E-11LOAD statement 7-143

INPUT keywordINPUT statement 7-122OPTIONS statement 7-166

INPUT NO WRAP keywordsOPTIONS statement 7-166

INPUT statement 2-20arr_count function 6-6EXIT INPUT 7-96infield function 6-14, 7-126NOENTRY fields 4-37syntax and notes 7-122terminating 7-125

INSERT cursorclosing 3-26, 7-25declaring 3-25, 3-37, 7-64flushing the insert buffer 7-25,

7-102guidelines for using 3-25opening 3-37, 7-156putting a row in the insert

buffer 7-177Insert key 7-166, I-5, I-23INSERT keyword

dbload command file E-12DECLARE statement 3-26, 7-64GRANT statement 7-115, E-14INPUT ARRAY statement 7-130LOAD statement 7-143OPTIONS statement 7-166REVOKE statement 7-187

INSERT statement 3-12DATETIME or INTERVAL

values J-8functions in 7-248inserting through a view 3-59running a PREPAREd 3-37SERIAL columns in 7-139syntax and notes 7-138with NULL values 3-57

INSTRUCTIONS section of formspecification

definition of 4-51DELIMITERS statement 4-52screen arrays 4-55SCREEN RECORD

statement 4-54screen records 4-54

INT data type 2-7, 3-8Integer constant 2-5INTEGER data type

acceptable values 2-7, 3-8, 7-50INT synonym 2-7, 3-8

12 Index

Page 949: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

with database columns 3-8with display fields 4-7with variables 2-7, 7-71

Intentional blanks (in multiple-linefields) 4-48

Interactive DebuggerDebugger path 1-50description of Intro-4, 1-65invoking 1-38, 1-53

Interactive modebcheck utility E-3dbload utility E-18

Interrupt key 2-23, 7-69, E-20INTERRUPT keyword, DEFER

statement 2-23, 7-69Interrupt signal 2-23, 7-69INTERVAL data type 2-9, J-5

acceptable values 7-51entered as a character string J-8entered as a literal value 4-30, J-6in dbload input files E-12manipulating arithmetically 2-36,

J-9using the UNITS keyword J-13with database columns 3-10with display fields 4-30with variables 2-9, 7-71

INTO keyworddbload command file E-13FETCH statement 3-17, 7-98FOREACH statement 3-16INSERT statement 7-139LOAD statement 7-143SELECT statement 3-29, 7-224,

7-245INTO TEMP clause

SELECT statement 7-8, 7-245with INSERT statement 7-139

int_flag variable 2-23, 7-69Inverse video (synonym for

reverse) 4-58INVISIBLE attribute 4-59, 7-77Invoking

4GL Compiler 1-6, 1-32, 1-614GL programs 1-6, 1-30, 1-52FORM4GL 1-17, 1-46, 4-63Interactive Debugger 1-38, 1-59Programmers Environment 1-6,

1-7, 1-36

IS keyword 2-13, 3-56, 7-60, 7-234ISAM record number 3-62Italics, in syntax

statements Intro-10items table in stores

database Intro-11, A-3

JJoins 4-63, 7-234

columns with the samename 7-235, G-1

in definition of a view 3-59multiple joins 7-235, G-5NULL column values 3-56, G-3outer join 3-61, 7-235, G-1self-join 7-235stores database columns A-5

KKernel locking 3-50, 7-197Key

Accept key 7-34, 7-124, 7-166arrow keys 7-35, 7-125function keys 7-125, 7-133, 7-167Help key 7-129, 7-166, E-27Interrupt 2-23, 7-34, 7-152Quit 2-23, 7-69restricted 7-125scrolling and editing 7-35, 7-166used in screen arrays 7-131, 7-166

KEY keywordINPUT ARRAY statement 7-132INPUT statement 7-123MENU statement 7-149OPTIONS statement 7-166

Keywords, notation in syntaxstatements Intro-10

LLABEL statement

GOTO 2-19, 7-114, 7-141, 7-213syntax and notes 7-141

LAST keywordFETCH statement 3-23, 7-98OPEN WINDOW statement

7-161OPTIONS statement 7-167REPORT statement 5-33

LEFT attribute 4-26LEFT MARGIN statement 5-12LENGTH keyword

LENGTH( ) function 2-38, 6-16,7-251

PAGE LENGTH statement 5-17Less ( < ) than symbol

in USING format strings 2-44relational operator 2-13, 7-33REVERSE attribute 4-42

LET statement 2-17CLIPPED 2-27, 3-31examples 2-38syntax and notes 7-142USING 2-46with string expressions 2-8

Library functions (INFORMIX-4GL)

arg_val 6-4arr_count 6-6arr_curr 6-7downshift 6-9errorlog 6-13err_get 6-10err_print 6-11err_quit 6-12infield 6-14, 7-126, 7-134length 6-16, 7-251num_args 6-17scr_line 6-18set_count 6-20showhelp 6-21startlog 6-23upshift 6-25

LIFO (last-in, first-out) queue 2-55LIKE data type specification 7-138

Index 13

Page 950: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

LIKE keywordDEFINE statement 2-10, 7-71DISPLAY LIKE attribute 4-31FORMONLY fields 4-19GLOBALS statement 7-112INITIALIZE statement 7-120RECORD data type 2-9SELECT statement 2-13, 7-231VALIDATE LIKE attribute 4-45VALIDATE statement 2-24, 7-211WHERE clause 7-231

LINE keywordOPEN WINDOW

statement 7-161OPTIONS statement 7-165SKIP statement 5-43

Line mode of a terminal 7-175LINENO expression 5-48LINES keyword

NEED statement 5-38SKIP statement 5-43

LOAD statement 3-29, 7-143Local variables 2-4, 5-7LOCK TABLE statement 3-40, 3-47

syntax and notes 7-146Locking

guidelines for using 3-47row-level 3-48, 7-139, 7-146table-level 3-49, 7-146, E-19

LOG keywordCREATE DATABASE

statement 3-43CREATE TABLE statement 7-50SELECT statement 7-245START DATABASE

statement 3-43Logging

error messages 6-23, E-19of temporary tables 7-50transactions 3-43

LOOKUP attribute ofPERFORM 4-63

Looping statements 5-4FOR 2-18, 7-38, 7-104FOREACH 2-18, 3-16, 7-106WHILE 2-19, 3-27, 7-216

Lowercase charactersDOWNSHIFT attribute 4-32, E-39downshift function 6-9

in 4GL statements 2-3, 4-11in syntax statements Intro-10SHIFT attribute 4-57, E-39UPSHIFT attribute 4-43, E-39upshift function 6-25

MMAGENTA attribute 4-26, 4-59,

I-19MAIN statement

description 2-17in source-code modules 1-33syntax and notes 7-148

manufact table in storesdatabase Intro-11, A-4

MARGIN keywordBOTTOM MARGIN

statement 5-16LEFT MARGIN statement 5-12RIGHT MARGIN statement 5-13TOP MARGIN statement 5-15WORDWRAP function 5-40

MATCHES keyword, in WHEREclause 4-58, 7-8, 7-33, 7-232

MAX aggregate function 3-64, 5-46,7-249

MDY function 2-39, 7-254Menu options of Programmers

Environment 1-7, 1-30MENU statement

CONTINUE MENU 7-38description 2-19EXIT MENU 7-96help messages 7-151syntax and notes 7-149

Menu-building utility 7-149Menu, programmer-defined

creating 7-149displaying options 7-38, 7-151naming menu options 7-150requesting help from 7-151selecting options 7-152

Message line 2-19, 7-154MESSAGE LINE keywords

OPEN WINDOWstatement 7-161

OPTIONS statement 7-154, 7-165

Message numbers in help files E-27MESSAGE statement 2-19

syntax and notes 7-154MIN aggregate function 3-64, 5-46,

7-249Minus ( - ) sign

arithmetic operator 2-11, 4-25,7-219

comment indicator 2-4delimiter in DATETIME

values 2-6, E-12delimiter in INTERVAL

values 2-6, E-12in USING format strings 2-45in window border 4-13, I-6unary operator 2-5, 2-6, 4-25

MINUTE keywordDATETIME qualifier 3-10, J-2INTERVAL qualifier 3-10, J-6

mkmessage utility 1-9, 1-38, E-27MODE ANSI database

comment indicators 2-4description of 3-6error handling 2-22implicit transactions 3-6, 3-43owner naming 3-7, 4-15specifying 3-42syntax checking 3-6, 3-64, 7-7table access privileges 3-41

MODE ANSI keywordsCREATE DATABASE

statement 3-43, 7-41START DATABASE

statement 3-42, 7-200MODE keyword

CREATE DATABASEstatement 3-43

LOCK TABLE statement 7-146SET LOCK MODE

statement 3-48, 7-197START DATABASE

statement 3-42MODIFY keyword, ALTER TABLE

statement 7-15Modify option

FORM Menu 1-15, 1-44, 4-61MODULE Menu 1-9, 1-39PROGRAM Menu 1-19, 1-49

14 Index

Page 951: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Module 2-18compiling 1-13, 1-42option of INFORMIX-4GL

Menu 1-9, 1-38running multi-module

programs 1-13, 1-42, 1-65MODULE Menu 1-26, 1-55Module variables 2-4MONEY data type

acceptable values 3-9, 7-50in dbload input files E-12with database columns 3-9with display fields 4-29, C-5with variables 2-8, 7-71

MONTH keywordDATETIME qualifier 3-10, J-2INTERVAL qualifier 3-10, J-5MONTH( ) function 2-40, 7-9,

7-255Multiple-column fields 4-21, 4-34,

4-42Multiple-database queries Intro-7Multiple-line fields 4-20, 4-47Multiple-module programs,

compiling 1-13, 1-27, 1-41, 1-50,1-56, 1-64

Multiple-statement preparedobjects 3-38, 7-172

Multiple-table forms 4-56Multiple-table view 3-60, 7-58

NNaming conventions

column 3-6, 7-51constraints 3-7, 7-49database 3-6, 7-41display fields 4-17, 4-18, 4-22field tags 4-11identifiers 2-4, 3-6objects in a MODE ANSI

database 3-7table 3-6, 7-51

NEED statement in REPORTstatement 5-38

New optionFORM Menu 1-17, 1-46MODULE Menu 1-12, 1-41

PROGRAM Menu 1-22, 1-51NEWLINE character 4-47, E-11NEXT FIELD clause

INPUT ARRAY statement 7-130Next key 7-166, I-5, I-23NEXT keyword

FETCH statement 3-22, 7-98MENU statement 7-150OPTIONS statement 7-166

NO keywordCREATE TABLE statement 7-50OPTIONS statement 7-166SELECT statement 7-245syscolval table 4-57

NO WRAP keywords, OPTIONSstatement 7-166

NOENTRY attribute 4-37NORMAL attribute 4-59, 7-77,

7-154NOT FOUND keywords

WHENEVER statement 2-22,7-213

NOT keywordALTER INDEX statement 3-53,

7-12Boolean operator 2-13, 3-55, 7-218SELECT statement 7-238SET LOCK MODE

statement 7-197WHERE clause 7-229

NOT NULL keywordsALTER TABLE statement 3-54,

7-14CREATE TABLE statement 3-54dbload utility E-14dbupdate utility E-25FORMONLY fields 4-19SELECT statement 2-13, 7-228

NOTFOUND code, statusvariable 3-63

NOTFOUND keywordstatus after FETCH 3-17, 3-22status after SELECT 3-63

NOUPDATE attribute ofPERFORM 4-63

NULL keyworddbload command file E-13INITIALIZE statement 2-15

NULL valuesaggregate functions 3-55, 3-64,

5-46, 7-250assigning 7-120definition of 2-5, 3-53in Boolean expressions 2-14, 3-55,

7-118, 7-229in columns 3-54, 7-144, 7-234in display fields 4-19, 4-29, 4-40in GROUP BY clause 3-56, 7-240in joined columns 3-56, G-3in number expressions 3-54in ORDER BY clause 3-56in string expressions 3-54, 4-29in WHERE clause 3-55, 7-228NOT NULL clause 3-54, 7-51,

7-228truth tables 3-55with dbload utility E-12with INSERT 3-57with UPDATE 3-57WITHOUT NULL INPUT 4-7

Number expression 2-11arithmetic operators in 2-11formatting 2-44, 4-33NULL values in 3-54

Number of rows processed 3-63NUMERIC data type 2-8, 3-9num_args function 6-17

OO symbol Intro-11Object file 1-35, 1-50, 1-72, E-30Object, naming in MODE ANSI

database 3-7OF keyword

AFTER GROUP OF controlblock 5-25

ARRAY data type 2-10BEFORE GROUP OF control

block 5-27DECLARE statement 3-17, 7-64DELETE statement 3-18, 7-73UPDATE statement 3-19, 7-207

OFF keyword, SET EXPLAIN 7-194ON EVERY ROW control

block 5-31

Index 15

Page 952: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

ON KEY clauseDISPLAY ARRAY

statement 7-60, 7-79INPUT ARRAY statement 7-130INPUT statement 6-22, 7-123PROMPT statement 7-173

ON keywordCONSTRUCT statement 7-32DISPLAY ARRAY statement 7-79GRANT statement 7-115PROMPT statement 7-173REPORT statement 5-8REVOKE statement 7-187SET EXPLAIN statement 3-52,

7-194ON LAST ROW control block 5-33OnLine database engine Intro-6,

7-7, C-7OPEN FORM statement 2-20

opening a closed form 7-28syntax and notes 7-159

OPEN statementsyntax and notes 7-156USING clause 3-36, 7-157with a SELECT cursor 3-16with an INSERT cursor 3-26,

7-157OPEN WINDOW statement 2-20

ATTRIBUTE clause 7-161syntax and notes 7-160

Operating systeminvoking the Compiler from 1-32,

1-61invoking the Programmers

Environment from 1-25, 1-30,1-54, 1-59

Operatorarithmetic 2-11range 7-34, 7-233relational 2-13string 2-12UNION 7-246

OPTION keywordCREATE VIEW statement 3-60,

7-57GRANT statement 7-116MENU statement 7-150

Options of 4GL menus 7-150

OPTIONS statement 2-20mkmessage utility E-27syntax and notes 7-165

OR keywordBoolean operator 2-13, 3-55COLOR attribute 4-25in WHERE clause 3-56, 7-234

ORDER BY clauseASC 3-56, 7-243DESC 3-56, 7-243INSERT statement 7-139multiple-column sorting 7-243prohibited in view definition 7-58REPORT statement 5-18, 5-25SELECT statement 7-243with NULL values 3-56

orders table in storesdatabase Intro-11, A-3

OTHERWISE keywordCASE statement 7-21

Outer joins 3-61, G-1OUTER keyword, SELECT

statement 3-62, 7-8, 7-218, 7-226,G-3

OUTPUT section of REPORTstatement 5-9

BOTTOM MARGIN 5-16LEFT MARGIN 5-12PAGE LENGTH 5-17REPORT TO 5-10REPORT TO PRINTER 5-10RIGHT MARGIN 5-13syntax 5-9, 7-184TOP MARGIN 5-15

OUTPUT TO REPORTstatement 2-21

guidelines for using 5-4syntax and notes 7-170

Overflow of a display field 2-46Owner naming 3-7, 7-226

ALTER TABLE statement 7-15and system catalogs 3-8CREATE SYNONYM

statement 7-47CREATE TABLE statement 7-51CREATE VIEW statement 7-57FORM4GL specification 4-15INITIALIZE statement 7-120

START DATABASEstatement 7-200

VALIDATE statement 7-211Owner of an object in a MODE

ANSI database 4-4, 4-60, 7-16,7-35

PPAGE HEADER control block 5-29,

5-34PAGE keyword

FIRST PAGE HEADER controlblock 5-29

PAGE HEADER controlblock 5-34

PAGE LENGTH statement 5-17PAGE TRAILER control

block 5-36SKIP statement 5-43

PAGE LENGTH statement 5-17PAGE TRAILER control block 5-36PAGENO expression 5-49Pages

of a help file message E-28of a report 5-9of a screen form 4-9, 4-63of menu options 7-150

Parameters of functions 2-56, 7-110Parentheses

in syntax statements Intro-10in USING format strings 2-45

Pattern matchingquery by example 7-33with equal ( = ) sign 7-33with LIKE 2-13, 7-231with MATCHES 2-13, 7-232

PAUSE statement, REPORTstatement 5-39

P-code compiler, function 1-61P-code runner 1-61

customized 1-68, 1-69Interactive Debugger 1-59specifying name and

location 1-50P-code version number 1-62, 1-64PERCENT aggregate function 5-46

16 Index

Page 953: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

PERFORM (INFORMIX-SQL)screens with INFORMIX-4GL 4-3, 4-63

Period ( . ) symboldelimiter in DATETIME

values 2-6, E-12delimiter in INTERVAL

values 2-6, E-12in help message source files E-27in USING format string 2-45prefix separator 2-24, 4-14range operator 7-34

PICTURE attribute 4-38, 4-57PIPE keyword

REPORT TO statement 5-10START REPORT statement 7-202

Planned_Compile option,PROGRAM Menu 1-23, 1-52

Plus ( + ) signarithmetic operator 2-11, 7-219in USING format strings 2-45in window border 7-163, I-6unary operator 2-5, 2-6

Popping functions (Clanguage) 2-55

Pound ( # ) signcomment indicator 2-3, I-3in FORMAT format strings 4-33in PICTURE format strings 4-38in USING format strings 2-44

PREPARE statement 3-28executing 3-33, 7-94guidelines for using 3-28multiple SQL statements 3-38,

7-172syntax and notes 7-171using placeholders for

values 3-30with a character string 3-30with a character variable 3-31

Preprocessor, invoking 1-31, 1-32Previous key 7-166, I-5, I-23PREVIOUS keyword

FETCH statement 3-23, 7-98OPTIONS statement 7-166

PRINT FILE statement inreports 5-42

PRINT statement

CLIPPED 2-27COLUMN 2-29REPORT statement 5-40USING 2-48

PRINTER keywordREPORT TO statement 5-10START REPORT statement 7-202

PRIOR keyword, FETCHstatement 3-17, 7-98

PRIVILEGES keyword 7-115Process isolation Intro-7Program array

array of records 2-10arr_count function 6-6arr_curr function 6-7defining 2-10, 7-71displaying rows in 7-79inserting rows 7-131set_count function 6-20table of functions for 7-135

Program examplesthat call C functions 1-70, 2-57

Program executioncommencing 1-59, 1-65, 6-4, 6-17from the command line 1-6, 6-4programs that call C

functions 1-34, 1-66terminating 6-12, 7-97with the Interactive

Debugger 1-65, 1-72Program features

assignment statements 2-17calling C functions 1-66, 2-55,

7-19commenting 2-3compiler 1-25, 1-32, 1-39compiling through Programmers

Environment 1-10, 4-60compiling, at operating system

level 1-61conditional statements 4-25, 7-21,

7-118error messages 2-21, 6-10, E-29executing a non-4GL

process 7-191expressions 2-11functions 2-24, 2-55, 6-3, 7-110help messages 6-21, 7-166, E-27identifiers 2-4

INFORMIX-4GL languageoverview 2-3

lettercase sensitivity 4-11looping statements 3-24MAIN program block 2-17, 7-148menus 7-149multi-module programs 1-13,

1-41owner naming 4-15program arrays 2-10program flow statements 2-18,

7-5records 4-54, 7-71, 7-138reports 2-21, 5-3, 7-184running, at operating system

level 1-64screen interaction

statements 2-19, 7-165statement types 2-16, 3-10, 7-5transactions 3-42types of program modules 1-10,

1-21, 1-29, 1-32, 1-50, 1-69Program flow statements 2-18, 7-5Program module, definition of 2-18Program organization

statements 2-17, 7-5Program records 7-72, 7-138Program specification

database 1-18, 1-48Programmers Environment

accessing 1-6, 1-7, 1-37COMPILE FORM Menu 1-16,

1-45COMPILE MODULE Menu 1-10,

1-39COMPILE PROGRAM

Menu 1-22, 1-51compiling a form 1-27, 1-56, 4-61compiling a program 1-12, 1-27,

1-41, 1-56correcting errors in a

program 1-11, 1-40creating a default form 4-61Debug option, MODULE

Menu 1-42Debug option, PROGRAM

Menu 1-53defining a program 1-26, 1-55definition of 1-6

Index 17

Page 954: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Drop option, PROGRAMMenu 1-24

Exit option, FORM Menu 1-18,1-47

Exit option, MODULEMenu 1-14, 1-43

Exit option, PROGRAMMenu 1-24, 1-53

files displayed 1-26, 1-64FORM Menu 1-14, 1-43, 4-61Generate option, FORM

Menu 1-16, 1-46in C Compiler version of 4GL 1-7in Rapid Development

System 1-36INFORMIX-4GL Menu 1-8, 1-37invoking the Debugger 1-38, 1-53menu options 1-31, 1-61modifying a form specification

file 1-15, 1-44MODULE Menu 1-9, 1-38NEW FORM Menu 1-17, 1-46NEW MODULE Menu 1-12, 1-41NEW PROGRAM Menu 1-22,

1-51Planned_Compile option,

PROGRAM Menu 1-23, 1-52PROGRAM Menu 1-18, 1-48Program_Compile option,

MODULE Menu 1-13, 1-41QUERY LANGUAGE Menu 1-25,

1-54Run option, MODULE

Menu 1-13, 1-42Run option, PROGRAM

Menu 1-24, 1-52Undefine option, PROGRAM

Menu 1-53Program_Compile option,

MODULE Menu 1-13, 1-41PROMPT LINE keywords

OPEN WINDOWstatement 7-161

OPTIONS statement 7-165Prompt line of a screen form 7-162PROMPT statement 2-19

syntax and notes 7-173Pseudo-code (= p-code) 1-5

PUBLIC keywordGRANT statement 3-41, 7-52,

7-116REVOKE statement 7-52, 7-188

Pushing functions (Clanguage) 2-55

PUT statementand the SQLCA record 3-28,

7-178and the status variable 3-28, 7-178FROM clause 3-38guidelines for using 3-26, 7-26syntax and notes 7-177

QQuery by example

CONSTRUCT 7-33PREPARE 3-30table of operators 7-33using the alternation

operator 7-33using the range operator 7-34using wildcard characters 7-34

Query optimizer 3-52, 7-194QUERYCLEAR attribute of

PERFORM 4-63Querying the database

compound queries 7-246cursors 3-13, 7-64, 7-156distributed across

databases Intro-7joins 3-51, 4-63, 7-234, G-1query by example 7-32relational operators 7-220searching for rows with NULL

values 3-56subqueries 3-56, 7-207, 7-237through views 3-58with SELECT 7-218

Question ( ? ) markplaceholder in PREPAREd

statements 3-30, 7-94, 7-171,7-178

wildcard 7-34, 7-232Quick Reference Card Intro-3Quit key 2-23, 7-69

QUIT keyword, DEFERstatement 7-69

quit_flag variable 2-23, 7-69Quotation ( " ) marks

around character pointer 1-68around character strings 2-5, 4-36around date-time value 2-6, 4-29around format strings 2-44, 2-46,

4-33, 4-38around pathnames 7-39, 7-50,

7-200

Rr4gl command 1-6, 1-54, 4-61r4gldemo script Intro-11, 1-6Range of values

COLOR attribute 4-25dbload utility E-14INCLUDE attribute 4-35query by example 7-34upscol utility 4-58, E-41WHERE clause 7-229

Rapid Development System versionof 4GL Intro-3, 1-5, 1-36

RDS (= Rapid DevelopmentSystem) 1-5

REAL data type 2-8, 3-9Record

definition of 2-9, 7-71in an array 4-54, 7-192passing to a function 7-111SQLCA global record 3-63with INSERT 7-138

RECORD keyworddefining program records 2-9,

7-71defining screen arrays 4-55defining screen records 4-54defining variables 7-71LIKE keyword 2-9, 7-71

Records in data files 7-143, 7-203,E-12

RECOVER TABLE statement 3-46,7-179

Recovery procedures Intro-7, 3-42RED attribute 4-26, 4-59, 7-77, I-19

18 Index

Page 955: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Relational operators 2-13, 4-25,7-220

RELATIVE keywordFETCH statement 3-17, 7-98

RENAME COLUMNstatement 3-12

syntax and notes 7-181RENAME TABLE statement 3-11

syntax and notes 7-182Report generation statements 2-21,

7-5REPORT statement 2-18

aggregate functions 5-44control blocks 5-23DEFINE section 5-5, 5-7displaying a report 5-9END REPORT keywords 5-5FORMAT section 5-5, 5-20grouping data 5-23ORDER BY section 5-5, 5-18ORDER EXTERNAL BY 5-18OUTPUT section 5-5, 5-9PRINT statement 5-40REPORT keyword 5-6running a report 5-4, 7-202SKIP statement 5-43statements in a report

routine 5-37structure 5-5syntax and notes 7-184

REPORT TO statement 5-10Report writer 5-3Reports, programmer-defined

aggregate functions 5-26calculations on groups 5-47counting rows 5-46default layout 5-21features 5-3formatting 5-20, 5-23, 7-184minimal report 5-6output of a report 5-9piping a report to a program 5-10printing data 5-40running a report 5-4sending output to a file 5-10sorting data 5-18, 7-185starting report processing 7-202steps for creating 5-4

REQUIRED attribute 4-40

Reserved linesComment line 4-27, 7-165default settings 7-161Error line 2-19, 2-23, 6-11, 6-12,

7-162, 7-165Form line 2-20, 7-162, 7-166Message line 2-19, 7-165Prompt line 2-19, 7-165

Reserved wordslisting D-1

RESOURCE access privilege 7-116RESOURCE keyword

GRANT statement 3-41, 7-116REVOKE statement 7-187

Return key 7-166RETURN keyword

FUNCTION statement 7-110RETURN statement 7-186RETURNING keyword

CALL statement 2-56, 7-19RUN statement 7-191

REVERSE attribute 4-26, 4-59, I-9description of 4-42multiple-column 4-21

REVOKE statement 3-40DBA 3-41syntax and notes 7-187

RIGHT attribute of PERFORM 4-63RIGHT MARGIN statement 5-13Ring menu 7-150ROLLBACK WORK statement

restoring previous database 3-42syntax and notes 7-189

ROLLFORWARD DATABASEstatement

definition of 3-42recovering a database 3-45syntax and notes 7-190

Row 3-5deleting from a table 3-18, 7-73determining row length E-24duplicates in a view 3-60inserting into a table 7-138locking 3-48, 7-99, 7-139ROWID 3-62unlocking 3-48updating 3-19, E-38

ROW keywordEVERY ROW statement 5-21INPUT ARRAY statement 7-130ON EVERY ROW control

block 5-31ON LAST ROW control

block 5-33Row number

in a database table 3-62in a program array 6-7, 6-20in a screen array 4-55, 6-18

ROWID value 3-62, 3-64ROWS keyword, OPEN WINDOW

statement 7-160Run menu option 1-31, 1-61Run option

MODULE Menu 1-13, 1-42PROGRAM Menu 1-24, 1-52

RUN statement 2-19, 7-191Runner, creating a customized 1-69Runner, invoking 1-5, 1-50, 1-61Running a 4GL program

command line 1-6, 1-34that calls C functions 1-34, 1-72using Debugger 1-61, 7-7

Run-time errors 2-21, 7-213

SSchema language 7-10Schema replication, using

dbschema E-22Scope of reference of identifiers 2-5Screen array 7-32, 7-75

definition of 4-55format of 4-12, 4-56identifying the current row 6-7,

6-18keys for scrolling and

editing 7-131scrolling rows of data 7-192table of functions for 6-3, 7-135

Screen display characteristicschanging attributes 4-59, 7-36,

7-77, 7-81, 7-83, 7-93, 7-127,7-136, 7-155, 7-168, 7-175

clearing the screen 7-23, I-4, I-22

Index 19

Page 956: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

default screen attributes 4-56,E-40

screen coordinates 4-8, 7-76,7-161

setting up screen attributes 4-22table of color and intensity

values 4-57Screen form 4-5

clearing values in the form 7-23closing 7-28dimensions 4-6, 4-8, 7-161displaying 7-83, 7-165displaying values in fields 7-75entering values in fields 7-32identifying the current field 6-14opening a 7-159specifying from the Programmers

Environment 1-14, 1-43, 4-61Screen interaction statements 2-19,

7-5SCREEN keyword

CLEAR statement 7-23CURRENT WINDOW

statement 7-60INSTRUCTIONS section of form

specification 4-4, 4-54SCREEN section of form

specification 4-8Screen record 7-32, 7-75

default screen record 4-54definition of 4-54moving rows through a screen

array 7-192SCREEN RECORD keywords 4-54SCREEN section of form

specificationdefinition of 4-8display field 4-10field delimiters 4-11, 4-52field tags 4-10field width 4-11for a multiple-table form 4-6graphics characters 4-12screen page layout 4-9

Screen-building utility 4-3SCROLL keyword

DECLARE statement 3-14, 7-64SCROLL statement 2-21, 7-192

scr_line function 6-18, 7-135

SECOND keywordDATETIME qualifier 3-10, J-2INTERVAL qualifier 3-10, J-6

SELECT clauseALL 7-222display label 7-8, 7-222DISTINCT and UNIQUE

keywords 7-222join conditions 7-234, G-1, G-4syntax and notes 7-222

SELECT cursoradvancing 3-17closing 3-17, 7-25declaring 3-14, 7-64opening 3-16, 7-156syntax and notes 3-13, 7-64

SELECT keyworddbload command file E-12DECLARE statement 3-14, 7-64GRANT statement 3-41, 3-60,

7-115, 7-204REVOKE statement 3-41, 7-187

SELECT statementaggregate functions in 7-249arithmetic operators in 7-219assigning a cursor 3-14, 7-64constructing with LET 7-172creating temporary tables 7-8,

7-245DATETIME or INTERVAL

values J-15defining a view 3-58, 7-57definition of 3-12, 7-193displaying results 5-3distributed across

databases Intro-7estimating CPU cost 3-52, 7-194expression in 7-219FROM clause 7-226functions in 2-24, 7-248GROUP BY clause 7-8, 7-240HAVING clause 7-242in a DECLARE statement 7-64in an INSERT statement 7-138in an UNLOAD statement 7-203INTO clause 3-29, 7-99, 7-107,

7-224INTO TEMP clause 3-58, 7-8,

7-245

joining columns with 3-51, 7-234LENGTH function 2-38, 7-251ORDER BY clause 3-18, 7-243overview of clauses 7-220relational operators 7-220SELECT clause 7-222self-join 7-235singleton SELECTs 7-224syntax and notes 7-193, 7-218UNION operator 7-246using multiple tables 7-220WHERE clause 7-228with an outer join 3-62, 7-235, G-1with multiple joins 7-235, G-5with subqueries 3-56, 7-237

Semicolon ( ; ) symbolin multiple-column display

fields 4-21in the description of a display

field 4-16statement terminator 7-172, E-14

SEQUENTIAL SCAN accessmethod 7-194

SERIAL data typeacceptable values 3-9, 7-51INSERT statement 4-37, 7-139program variables 2-9retrieved by

SQLCA.SQLERRD[2] 3-63UPDATE statement 7-207with database columns 3-9with display fields 4-19, 4-37

SET EXPLAIN statement 3-52syntax and notes 7-194with joins G-10

SET keyword, UPDATEstatement 7-206

SET LOCK MODE statement 3-48,7-197

kernel locking 3-50set_count function

guidelines for using 7-80syntax and usage 6-20with INPUT ARRAY 7-135

sg1 terminal specification 7-77,7-127, 7-136, 7-176, I-4, I-18

SHARE keywordLOCK TABLE statement 3-49,

7-146

20 Index

Page 957: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Shared memory Intro-6, 3-48, 7-197SHIFT attribute 4-57showhelp function 6-21, E-29Single-field INTERVAL value 2-6,

4-30SIZE keyword, form

specification 4-9SKIP statement in reports 5-43SLEEP statement 2-19, 7-199SMALLFLOAT data type

acceptable values 2-8, 3-9, 7-50REAL synonym 2-8, 3-9with database columns 3-9with FORMAT attribute 4-33with variables 2-8, 7-71

SMALLINT data typeacceptable values 2-7, 3-8, 7-50with database columns 3-8with variables 2-7, 7-71

SOME keyword, SELECTstatement 7-237

Sorting dataDATE columns 7-52in a report 5-18in an index 7-12multiple-column sorting 7-243with NULL values 3-56with ORDER BY 5-25, 7-243

Source modules 1-32, 1-61, 1-63Source path 1-50, C-6SPACE keyword 5-50Spacebar 7-150Spaces

in WORDWRAP fields 5-52SPACES keyword 5-50sqexplain.out file 3-52, 7-194SQL

ALTER INDEX statement 3-12,7-12

ALTER TABLE statement 3-11,7-14

BEGIN WORK statement 3-43,7-18

CLOSE DATABASEstatement 3-11, 7-27

CLOSE statement 3-17, 3-26COMMIT WORK statement 3-43,

7-31

CREATE AUDIT statement 3-45,7-39, 7-179

CREATE DATABASEstatement 3-11, 7-41

CREATE INDEX statement 3-12,7-44

CREATE SCHEMAAUTHORIZATIONstatement 7-10

CREATE SYNONYMstatement 3-11, 7-47

CREATE TABLE statement 3-11,7-49

CREATE VIEW statement 3-11,7-57

DATABASE statement 3-11, 7-62DECLARE statement 3-14, 3-26,

3-29, 7-64DELETE statement 3-12, 7-73DROP AUDIT statement 3-45,

7-85, 7-179DROP DATABASE

statement 3-11, 7-86DROP INDEX statement 3-12,

7-88DROP SYNONYM

statement 3-12, 7-89DROP TABLE statement 3-11,

7-90DROP VIEW statement 3-11, 7-91EXECUTE statement 3-28, 7-94FETCH statement 3-16, 7-98FLUSH statement 3-26, 7-102FOREACH statement 3-16FREE statement 3-39, 7-109GRANT statement 3-40, 7-115INSERT statement 3-12, 7-138LOAD statement 3-12, 7-143LOCK TABLE statement 3-40,

7-146OPEN statement 3-16, 3-26PREPARE statement 3-28, 7-171PUT statement 3-26, 7-177RECOVER TABLE

statement 3-46, 7-179RENAME COLUMN

statement 3-12, 7-181RENAME TABLE statement 3-11,

7-182

REVOKE statement 3-40, 7-187ROLLBACK WORK

statement 7-189ROLLFORWARD DATABASE

statement 7-190SELECT statement 3-12, 7-64,

7-193, 7-203, 7-218SET EXPLAIN statement 7-194SET LOCK MODE

statement 7-197START DATABASE

statement 7-200UNLOAD statement 3-12, 7-203,

E-11UNLOCK TABLE statement 3-40,

7-205UPDATE statement 3-12, 7-206UPDATE STATISTICS

statement 3-12, 7-210WHENEVER statement 2-21,

7-213SQL language 3-5

accessing from the ProgrammersEnvironment 1-25, 1-54

ambiguity with INFORMIX-4GLidentifiers 3-7

audit trails 3-45, 7-39, 7-85, 7-179data access statements 3-40, 7-6data definition statements 3-11,

7-6data integrity statements 3-42, 7-6data manipulation

statements 3-12, 7-6dynamic management

statements 3-28identifiers 3-6, 3-28interactive query language 1-8,

1-37, 3-5, 4-63statements supported only on

INFORMIX-SE 7-6testing statement execution 3-63transactions 3-42update notes for Version 1.10

users 3-54SQL version number 1-33, 1-62SQLAWARN characters 3-6, 3-64,

7-213

Index 21

Page 958: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

SQLCA recorddefinition of 3-63examined by WHENEVER 2-22set by CLOSE 3-28set by FLUSH 3-28set by PUT 3-28, 7-178SQLAWARN 3-6, 3-64, 7-213SQLCODE 3-17, 3-63, 7-145, 7-178SQLERRD 3-28, 3-63, 7-25, 7-145,

7-157sqlconv utility E-31SQLERROR keyword 7-213SQLEXEC environment

variable C-7SQLWARNING keyword 7-213Stack, in calling C functions 2-55START DATABASE statement 3-42

syntax and notes 7-200WITH LOG IN 3-43

START REPORT statement 2-21directing output 5-10syntax and notes 7-202

startlog function 2-22, 6-23state table in stores

database Intro-12, A-4Statement identifier 3-28, 7-94,

7-109Statement label 7-114, 7-141, 7-213Statement syntax

ALTER INDEX 7-12ALTER TABLE 7-14BEGIN WORK 7-18CALL 7-19CASE 7-21CLEAR 7-23CLOSE 7-25CLOSE DATABASE 7-27CLOSE FORM 7-28CLOSE WINDOW 7-30COMMIT WORK 7-31CONSTRUCT 7-32CONTINUE 7-38CREATE AUDIT 7-39CREATE DATABASE 7-41CREATE INDEX 7-44CREATE SYNONYM 7-47CREATE TABLE 7-49CREATE VIEW 7-57CURRENT WINDOW 7-60

DATABASE 7-62DECLARE 7-64DEFER 7-69DEFINE 7-71DELETE 7-73DISPLAY 7-75DISPLAY ARRAY 7-79DISPLAY FORM 7-83DROP AUDIT 7-85DROP DATABASE 7-86DROP INDEX 7-88DROP SYNONYM 7-89DROP TABLE 7-90DROP VIEW 7-91ERROR 7-92EXECUTE 7-94EXIT 7-96FETCH 7-98FINISH REPORT 7-101FLUSH 7-102FOR 7-104FOREACH 7-106FREE 7-109FUNCTION 7-110GLOBALS 7-112GOTO 7-114GRANT 7-115IF 7-118INITIALIZE 7-120INPUT 7-122INPUT ARRAY 7-129INSERT 7-138LABEL 7-141LET 7-142LOAD 7-143LOCK TABLE 7-146MAIN 7-148MESSAGE 7-154OPEN 7-156OPEN FORM 7-159OPEN WINDOW 7-160OPTIONS 7-165OUTPUT TO REPORT 7-170PREPARE 7-171PROMPT 7-173PUT 7-177RECOVER TABLE 7-179RENAME COLUMN 7-181RENAME TABLE 7-182

REPORT 7-184RETURN 7-186REVOKE 7-187ROLLBACK WORK 7-189ROLLFORWARD

DATABASE 7-190RUN 7-191SCROLL 7-192SELECT 7-193, 7-218SET EXPLAIN 7-194SET LOCK MODE 7-197SLEEP 7-199START DATABASE 7-200START REPORT 7-202UNLOAD 7-203UNLOCK TABLE 7-205UPDATE 7-206UPDATE STATISTICS 7-210VALIDATE 7-211WHENEVER 7-213WHILE 7-216

Statement typeassignment 2-17, 7-5cursor manipulation 3-13, 7-6data access 3-40, 7-6data definition 3-11, 7-6data integrity 3-42, 7-6data manipulation 3-12, 7-6data validation 2-23dynamic management 3-28, 7-6error and exception

handling 2-21program flow 2-18, 7-5program organization 2-17, 7-5report generation 2-21, 7-5screen interaction 2-19, 7-5variable definition 2-17, 7-5

status variable 2-22definition of 3-63NOTFOUND code 2-22, 3-17,

3-22, 7-99, 7-213with cursors 3-28with err_get function 6-10with err_print function 6-11with err_quit function 6-12with INITIALIZE 7-121with VALIDATE 7-212

STEP keyword, FORstatement 7-104

22 Index

Page 959: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

stock table in storesdatabase Intro-11, A-4

STOP keyword, WHENEVERstatement 7-213

stores databasecustomer table Intro-11, A-2data values A-9items table Intro-11, A-3join columns A-5manufact table Intro-11, A-4orders table Intro-11, A-3overview A-1state table Intro-12, A-4stock table Intro-11, A-4structure of tables A-2, A-5tables in Intro-11, A-2

String expression 2-12CLIPPED keyword 2-27concatenation operator 7-172constants 2-5length 2-38, 7-251NULL values in 4-19substring 2-12, 4-18table of operators 2-12USING keyword 2-44

Structure definition file,function 1-66

Subquery 3-56, 3-59, 7-222, 7-237,7-247

Subscriptevaluating with cursors 7-67of a CHAR column 4-18, 7-220

Substring 2-12, 4-18, 7-142SUM aggregate function 2-48, 3-64,

5-46, 7-249Synonym

for a table 3-11, 7-47, 7-226, E-22removing a synonym 3-12, 7-89rules for owner naming 3-7

Syntax checking, ANSI 1-32, 1-62,3-6

Syntax conventions Intro-9Syntax of command line to compile

a 4GL source file 1-32, 1-61syscolatt table 4-56

changing color names 4-58, I-19color and intensity values 4-57,

E-40creating with upscol 4-60, E-37

schema 4-57use by FORM4GL 4-17, 4-56with DISPLAY LIKE 4-31

syscolval table 2-24, 4-56as used by INITIALIZE 4-58,

7-121comparing values of

variables 7-211creating with upscol 4-60, E-37data validation 2-23, 4-58, 7-211schema 4-57use by FORM4GL 4-17, 4-56with VALIDATE LIKE

attribute 4-45syspgm4gl files 1-18, 1-48System catalogs

creating 3-11, 7-41described 3-5, B-1querying when MODE ANSI 3-8syscolauth B-3syscolumns 3-58, 7-138, B-2sysconstraints 7-16, 7-53, B-5sysdepend B-4sysindexes B-3syssynonyms B-4syssyntable B-5systabauth B-3systables 4-15, 7-210, B-2sysusers B-4sysviews 3-58, B-5updating 3-12

TTable 3-5

access methods 3-52, 7-194access privileges 3-41, 7-115, E-22adding a column 7-14adding a constraint 7-16adding a row 7-138, 7-143, E-11alias for table name 4-14, 4-60,

7-35, 7-226audit trails 3-42, 7-39changing the data type of a

column 7-14creating 7-49, E-22creating a synonym 7-47, E-22current 4-63

display label 7-223dominant 3-62, G-2filename 7-50, E-2guidelines for indexing 3-51joining tables 3-52, 7-234, A-5,

G-2locking 3-49, 7-146, 7-208, E-19modifying a row 3-59, 7-206naming conventions 3-6, 7-51not logging temporary 7-50outer join 3-61, 7-235, G-1removing a column 7-14removing a constraint 7-16removing a synonym 3-12, 7-89removing a table 7-90renaming 7-182revoking user access 7-188rules for owner naming 3-7structure in stores database A-2subservient 3-62, G-2temporary 3-58, 7-223, 7-245,

7-247unlocking 3-40, 3-47, 7-205

TABLES section of formspecification

definition of 4-4, 4-14Tape block size E-6TEMP keyword

CREATE TABLE statement 7-10,7-49

SELECT statement 3-58, 7-8,7-245

termcap file 4-13, I-2TERMINFO environment

variable I-20, I-25terminfo files 4-13, I-20TEXT data type Intro-7Text editor 1-11, 1-15, 1-31, 1-40,

1-45, 1-61THEN keyword, IF statement 7-118THROUGH keyword 2-15, 4-55THRU keyword 2-15, 4-55TIME function 2-41TO keyword

ALTER INDEX statement 3-53,7-12

CURRENT function 2-30, 7-258DATETIME literals 2-6, 4-30, J-2DISPLAY ARRAY statement 7-79

Index 23

Page 960: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

DISPLAY statement 2-15EXTEND function 2-35, 7-260GRANT statement 3-32, 7-115INCLUDE attribute 4-35INITIALIZE statement 2-15,

7-120INTERVAL literals 2-6, 4-30, J-5RENAME COLUMN

statement 7-181RENAME TABLE

statement 7-182REPORT TO statement 5-10SET LOCK MODE

statement 3-50, 7-197SKIP statement 5-43START REPORT statement 7-202UNLOAD statement 7-203WHENEVER statement 7-213

TODAY function 2-42, 3-65, 4-30TOP MARGIN statement 5-15, 5-29TOP OF PAGE keywords 5-43TRAILER keyword, REPORT

statement 5-36Transaction

committing modifications 3-42,7-31

comparison with audit trails 3-47cycle 3-43definition of 3-42explicit 3-44, 7-41, 7-200implicit 3-43, 7-41, 7-200log 3-43, 7-42, 7-200log file maintenance 3-45recovering transactions 3-42,

7-190row locking 3-44, 7-139singleton 3-44, 7-139starting 3-44, 7-18statements for specifying 3-42undoing modifications 3-42,

7-189usage in MODE ANSI 3-43

Transfer of database files E-6, E-11TRUE (Boolean constant) 2-5, 3-55,

4-25Truncation of data 3-64, 4-48, 7-80,

E-15Truth values 2-5, 3-55, 7-237, 7-238

Twenty-Minute Guide Intro-3TYPE keyword, FORMONLY

fields 4-19

UUndefine option, PROGRAM

Menu 1-53UNDERLINE attribute 4-26, 4-59,

I-9UNION operator 3-58, 7-58, 7-246UNIQUE constraint 7-139, E-14UNIQUE keyword

aggregate functions 7-250ALTER TABLE statement 7-14CREATE INDEX statement 7-44CREATE TABLE statement 7-49SELECT statement 7-8, 7-222

UNITS keyword 2-43, 4-30, J-13SELECT statement 7-8

UNIX permissions E-14UNKNOWN (Boolean

constant) 2-14, 3-55UNLOAD statement 3-29, 7-203,

E-11UNLOCK TABLE statement 3-40,

3-47syntax and notes 7-205

UP keywordSCROLL statement 7-192syscolval table 4-57, E-39

UPDATE keywordDECLARE statement 3-17, 7-64GRANT statement 3-41, 7-115REVOKE statement 7-187UPDATE STATISTICS

statement 7-210UPDATE statement

data conversion in 7-208DATETIME or INTERVAL

values J-15examples 3-18functions in 7-248locking rows 3-48subqueries 7-207syntax and notes 7-206updating through a view 3-59

WHERE CURRENT OFclause 3-19

with NULL values 3-57UPDATE STATISTICS

statement 3-12, 7-210UPDATE SYSCOL Menu

(upscol) E-37Uppercase characters

DOWNSHIFT attribute 4-32, E-39downshift function 6-9in 4GL statements 2-3, 4-11in syntax statements Intro-10SHIFT attribute 4-57, E-39UPSHIFT attribute 4-43, E-39upshift function 6-25

upscol utility 2-24, 4-59, E-37UPSHIFT attribute 4-43, 7-35, E-39upshift function 6-25USER function 3-65, 7-219User status and privileges 3-41USING keyword

DISPLAY statement 7-76EXECUTE statement 3-33, 7-94OPEN statement 3-36, 7-156PRINT statement 2-47, 5-40string operator 2-44

Utility programsbcheck E-2dbexport E-6dbload E-11, E-33dbschema E-22dbupdate E-25mkmessage E-27sqlconv E-31upscol 2-24, 4-56, E-37

VV command-line option 1-33, 1-62VALIDATE LIKE attribute 4-15,

4-45VALIDATE Menu (upscol) E-39VALIDATE statement 2-24, 4-58,

7-211VALUES keyword

dbload command file E-14INSERT statement 7-138

VARCHAR data type Intro-7

24 Index

Page 961: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

Variable 2-6as a parameter 2-17, 7-110binding to database and

forms 2-14data types 2-7, 7-71declaring a 2-4, 5-5, 7-71global 2-4, 7-112in REPORT statement 5-5int_flag 2-23, 7-69local 2-4, 7-110module 2-4naming conventions 2-4quit_flag 2-23, 7-69scope of reference 2-4statements for assigning

values 2-17statements for defining 2-17status variable 2-22, 3-63with the same name 7-111

Variable definition statements 7-5VERIFY attribute 4-46, 4-57Version 1 database

conversion to Version 2 E-25Version numbers of SQL

software 1-33, 1-62Versions of 4GL Intro-3, 1-5Vertical ( | ) bar

field separator in files 7-203, E-17field separator in forms 4-53graphics character 4-13, I-6, I-25in termcap specifications I-3in window border 7-163, I-6syntax convention Intro-10with CONSTRUCT 7-33

Viewaccess privileges 3-60, 7-117, E-22creating 3-58, 7-57, E-22creating a synonym 7-47, E-22data constraints 3-60definition and uses 3-57, 7-57deleting 3-58, 7-91guidelines for naming 7-58limitations 3-58, 7-16, 7-57modifying the database

through 3-59querying the database

through 3-58

rules for owner naming 3-7virtual column 3-59, 7-58with duplicate rows 3-60

WWAIT keyword, SET LOCK MODE

statement 3-50, 7-197WARNING keyword, WHENEVER

statement 2-22, 3-64, 7-213Warning messages 1-33, 7-7, 7-213WEEKDAY function 2-53, 7-256WHEN keyword, CASE

statement 7-21WHENEVER statement

ERROR keyword 2-22guidelines for using 2-22scope of reference 2-22, 7-214syntax and notes 7-213trapping errors 2-22, E-29trapping warnings and NOT

FOUND 2-22WARNING keyword 2-22, 7-213

WHERE clauseaggregate functions 5-47, 7-248ALL 7-237AND 7-234ANY 7-237BETWEEN 3-65, 7-229comparison condition 7-228ESCAPE 7-231, 7-233EXISTS 7-238IN 7-230, 7-238IS NULL 7-234joining columns in 7-234, G-1LIKE 7-231MATCHES 7-8, 7-232NOT 7-218NULL values 3-55, 7-234OR 7-234pattern matching in 7-34, 7-232ranges in 7-34, 7-229relational operators in 2-13, 7-229search conditions 7-34, 7-218,

7-228sets in 4-58, 7-230SOME 7-237syntax and notes 7-228

with a subquery 7-222, 7-237with COLOR attribute 4-25, 4-63,

E-41with DELETE 7-73with SELECT 7-228with UPDATE 7-206

WHERE CURRENT OF keywordsDELETE statement 3-18, 7-73UPDATE statement 3-19, 7-207

WHILE statement 2-19CONTINUE WHILE 7-38EXIT WHILE 7-96syntax and notes 7-216

WHITE attribute 4-26, 4-59, 7-77,I-19

Wildcard character 7-34, 7-232Window

attributes 7-161automatic sizing 7-161border 7-162, I-6, I-24changing the current

window 7-60clearing of text 7-23clearing the background

screen 7-23closing 7-30color 7-163, 7-168current 7-60, 7-161dimensions 7-161displaying a form 7-161displaying a menu 7-150locating on screen 7-161multiple windows 7-60opening 7-160reserved lines in 7-161, 7-165stack 7-30, 7-61, 7-164

WINDOW keywordCLEAR statement 7-23CURRENT WINDOW

statement 7-60OPEN WINDOW

statement 7-160OPTIONS statement 7-168

WITH CHECK OPTION clauseCREATE VIEW statement 3-60,

7-57WITH FORM clause, OPEN

WINDOW statement 7-161

Index 25

Page 962: Manual Informix

O QCA B D E F G H I J K L M N P R S T U V W X Y Z

WITH GRANT OPTION keywordsGRANT statement 3-60, 7-116

WITH HOLD keywordsDECLARE statement 3-14, 3-20,

7-64WITH keyword

CREATE DATABASEstatement 3-43

CREATE TABLE statement 7-50CREATE VIEW statement 3-60,

7-57DECLARE statement 3-14, 7-64GRANT statement 3-60, 7-116OPEN WINDOW

statement 7-160START DATABASE

statement 3-43WITH LOG IN keywords

CREATE DATABASEstatement 7-41

START DATABASEstatement 7-200

WITH NO LOG keywordsCREATE TABLE statement 7-50SELECT statement 7-245

WITHOUT DEFAULTS keywordsINPUT ARRAY statement 4-29,

6-20, 7-129INPUT statement 4-29, 7-122

WITHOUT NULL INPUTkeywords

DATABASE section 4-29WITHOUT WAITING keywords

RUN statement 7-191WORDWRAP attribute 4-21, 4-47WORDWRAP function

in a PRINT statement 5-40syntax and notes 5-51

WORK keywordBEGIN WORK statement 3-42,

7-18COMMIT WORK statement 3-42ROLLBACK WORK

statement 3-42WRAP keyword, OPTIONS

statement 7-166

XX symbol in PICTURE format

strings 4-38xmc1 terminal specification 7-77,

7-127, 7-136, 7-176, I-21XOFF key 7-125

YY symbol

formatting DATE values 2-46,C-3

option of bcheck utility E-3values in syscolatt table 4-58, E-40

YEAR keywordDATETIME qualifier 2-9, 3-10,

4-20, E-12, J-2, J-5INTERVAL qualifier 2-9, 3-10with CURRENT function 2-31,

2-36, 7-259with EXTEND function 2-36,

7-260with UNITS keyword 2-43, J-15YEAR( ) function 2-54, 7-9, 7-257

YELLOW attribute 4-26, 4-59, 7-77,I-19

YES keyword in syscolvaltable 4-57, E-39

ZZA function (termcap file) I-9, I-17Zero

default INTERVAL value 4-7, J-9default number value 4-19for Boolean FALSE 2-14inserting SERIAL values 7-139value of status variable 2-22,

7-213zero fill ( & ) character in output

fields 2-46Zero or more characters, symbol

for 7-34, 7-231, 7-232ZEROFILL attribute of

PERFORM 4-63

26 Index