RPG400 Course Material

207
Table of Contents: Chapter I :AS/400 Highlights.................................................................. 10 Introduction :...............................................10 Technology-Independent Machine Interface...................10 Operating System OS/400....................................11 Single-Level Storage....................................... 11 Logical Partitioning (LPAR)................................12 Objects.................................................... 12 AS/400 Processing Environment................................15 What is a job?........................................... 15 Job Description:........................................... 15 Subsystem.................................................. 15 Job Queues................................................. 15 Output Queues.............................................. 15 Type of Jobs............................................... 16 AS/400 Security..............................................17 Security at object level:.......................................... 17 Security Functions........................................... 18 Security Levels............................................ 19 Application Development Tools (ADT)..........................20 Program Development Manager (PDM)..........................20 Source Entry Utility (SEU).................................23 Data File Utility (DFU)....................................24 Chapter II –Libraries.............................................................................. 25 Library Categories...........................................25 Library List:................................................26 Library commands:............................................26 Library List Commands:.......................................27 Chapter III: AS/400 Database................................................................ 28 File Types:..................................................28 Database Files:..............................................29 Access paths:................................................. 29 Physical Files:................................................. 29 Logical Files:..................................................30 Types Of Logical Files...........................................31 Join Logical File................................................31 1 of 207

Transcript of RPG400 Course Material

Page 1: RPG400 Course Material

Table of Contents:

Chapter I :AS/400 Highlights................................................................................10Introduction :.............................................................................................................................10

Technology-Independent Machine Interface.........................................................................10Operating System OS/400.....................................................................................................11Single-Level Storage.............................................................................................................11Logical Partitioning (LPAR).................................................................................................12Objects...................................................................................................................................12

AS/400 Processing Environment...............................................................................................15What is a job?......................................................................................................................15Job Description:.....................................................................................................................15Subsystem..............................................................................................................................15Job Queues.............................................................................................................................15Output Queues.......................................................................................................................15Type of Jobs...........................................................................................................................16

AS/400 Security.........................................................................................................................17Security at object level:.........................................................................................................17Security Functions.................................................................................................................18Security Levels......................................................................................................................19

Application Development Tools (ADT)....................................................................................20Program Development Manager (PDM)...............................................................................20Source Entry Utility (SEU)....................................................................................................23Data File Utility (DFU).........................................................................................................24

Chapter II –Libraries..............................................................................................25Library Categories.....................................................................................................................25Library List:...............................................................................................................................26Library commands:....................................................................................................................26Library List Commands:............................................................................................................27

Chapter III: AS/400 Database...............................................................................28File Types:.................................................................................................................................28Database Files:...........................................................................................................................29

Access paths:.........................................................................................................................29Physical Files:.......................................................................................................................29Logical Files:.........................................................................................................................30Types Of Logical Files...........................................................................................................31Join Logical File....................................................................................................................31Non - Join Logical File:........................................................................................................32

Field Reference Files:................................................................................................................33Importance of using Field Reference Files............................................................................33

Naming Conventions.................................................................................................................33Chapter IV: Data Description Specification (DDS)..............................................35

Defining Physical Files..............................................................................................................35Components of DDS..............................................................................................................36Physical File Keywords.........................................................................................................37

1 of 150

Page 2: RPG400 Course Material

File Level Keywords..............................................................................................................37Record Level Keywords.........................................................................................................38Field Level Keywords............................................................................................................38Key Field Level Key words....................................................................................................39

Defining Logical Files...............................................................................................................40Logical file Keywords...........................................................................................................41File Level Keywords..............................................................................................................41Record Level Keywords.........................................................................................................42Join Logical Files..................................................................................................................43Join Level Keywords..............................................................................................................44

Examples of database files in DDS:..........................................................................................45Example of a field reference file:...........................................................................................45Example of a physical file with a new record format:...........................................................46Example of a logical file specifying multiple formats and new keys:....................................47Example of a logical file specifying a new record format:....................................................47Example of a join logical file:...............................................................................................48

DDM Files.................................................................................................................................49Chapter V: SDA and Display Files........................................................................50

Screen Design Aid(SDA):.........................................................................................................50Adding fields..........................................................................................................................52Adding constants....................................................................................................................52Adding fields from a database file.........................................................................................52Moving, Copying and Shifting fields.....................................................................................53Date and Time keywords.......................................................................................................54Display Files:.........................................................................................................................54

Chapter VI: RPG/400.............................................................................................61RPG/400 Language Concepts....................................................................................................61RPG/400 Specifications.............................................................................................................62

H CONTROL SPECIFICATION.........................................................................................63F FILE SPECIFICATION..................................................................................................63E EXTENSION SPECIFICATION......................................................................................63L LINE COUNTER SPECIFICATION...............................................................................63I INPUT SPECIFICATION...............................................................................................63C CALCULATION SPECIFICATION...............................................................................63O OUTPUT SPECIFICATION..........................................................................................63

RPG/400 Operation Codes (OPCODES):.................................................................................64Arithmetic Operations...........................................................................................................64

ADD (Add Statement)..............................................................................................64 Z-ADD (Zeroise and add)..........................................................................................65 SUB (Subtract statement)..........................................................................................65 Z-SUB (Zeroise and subtract)....................................................................................65 MULT (Multiply).....................................................................................................66 DIV (Divide)..............................................................................................................66 MVR (Move remainder)...........................................................................................66 SQRT (Square root)..................................................................................................67

2 of 150

Page 3: RPG400 Course Material

Move Operations:..................................................................................................................67 MOVE (Move)..........................................................................................................67 MOVEL (Move left)..................................................................................................67

Compare Operations.............................................................................................................67 IFxx (If condition)....................................................................................................68 DOUxx (Do until)......................................................................................................69 DOWxx (Do while)...................................................................................................70 WHxx (When)...........................................................................................................70 COMP (Compare)......................................................................................................71

Declarative Operations.........................................................................................................71 PLIST ( Parameter list)..............................................................................................71 PARM (Parameter)...................................................................................................71 KFLD (Key Field)....................................................................................................72 KLIST (Key list)........................................................................................................72 DEFN (Definition).....................................................................................................72 TAG(Tag)..................................................................................................................73

Initialization Operations........................................................................................................73 CLEAR (Clear)..........................................................................................................73 RESET (Reset)...........................................................................................................74

String Operations...................................................................................................................74 CAT (Concatenate Two Character Strings)...............................................................74 CHECK (Check Characters)......................................................................................74 CHEKR (Check Reverse)..........................................................................................75 SCAN (Scan Character String)..................................................................................76 XLATE (Translate)....................................................................................................76 SUBST (Substring)....................................................................................................77

Subroutine Operations...........................................................................................................77 CASxx (Compare and execute subroutine)...............................................................77 EXSR(Execute Subroutine).......................................................................................78 BEGSR(Begin Subroutine)........................................................................................78 ENDSR(End Subroutine)...........................................................................................78

Indicator Operations.............................................................................................................79 SETON (Set on indicator).........................................................................................79 SETOF (Set off indicator).........................................................................................79

Structured Programming Operations....................................................................................79 ORxx (Or condition)..................................................................................................80 ANDxx (And condition)............................................................................................80 ELSE (Else)...............................................................................................................80 END (End).................................................................................................................81 ENDyy (End Condition)............................................................................................81 DO (Do Iteration)......................................................................................................81 SELEC (Select)..........................................................................................................82 OTHER (Other).........................................................................................................82 ITER (Iterate).............................................................................................................82 LEAVE (Leave).........................................................................................................82

3 of 150

Page 4: RPG400 Course Material

File Operations......................................................................................................................83 OPEN (Open File for Processing).............................................................................83 CLOSE (Close Files).................................................................................................83 SETLL (Set Lower Limits)........................................................................................84 SETGT (Set Greater Than)........................................................................................85 READ (Read a Record).............................................................................................85 READE (Read Equal Key)........................................................................................86 READP(Read a Previous Record)............................................................................86 REDPE (Read Prior Equal).......................................................................................87 CHAIN (Random Retrieval from a File)...................................................................87 WRITE (Create New Records)..................................................................................87 UPDAT (Modify Existing Record)...........................................................................88 DELET (Delete Record)............................................................................................88

Calling Operations................................................................................................................89 CALL (Call a Program).............................................................................................89 PARM (Identify Parameters).....................................................................................89 PLIST (Identify a Parameter List).............................................................................90

Branching Operations...........................................................................................................91 GOTO(Go to).............................................................................................................91 ITER (Iterate).............................................................................................................91 LEAVE (Leave).........................................................................................................92

Array Operations...................................................................................................................92 MOVEA (Move array)..............................................................................................92 XFOOT (Array Total)................................................................................................93 LOKUP (Lookup)......................................................................................................93 SORTA (Sort array)...................................................................................................94

Data Area Operations............................................................................................................94Commitment Control Operations..........................................................................................94

COMIT (Commit)......................................................................................................94 ROLBK (Roll Back)..................................................................................................94

Examples For File processing:...................................................................................................95RPG syntax to process an externally defined Physical File:..............................................95RPG syntax to process a Program defined Physical File:.................................................95

Chapter VII: Subfiles.............................................................................................97Components of Subfile..............................................................................................................97

Subfile format {SFL}..............................................................................................................97Subfile control format {SFLCTL}..........................................................................................97Subfile Keywords...................................................................................................................98

Subfile Data Description Specification :..................................................................................99Handling Subfiles in RPG Programs.......................................................................................100

File Declarations.................................................................................................................100Calculation Specification.....................................................................................................100Steps Involved In Subfile Programming :.........................................................................100

Multi page subfiles:.................................................................................................................101Subfile Load Options- Pros and Cons.................................................................................101

4 of 150

Page 5: RPG400 Course Material

Load all Subfile:..................................................................................................................101RPG program for load all subfiles.......................................................................................102Expanding Subfile:...............................................................................................................104Single Page Subfile:.............................................................................................................106

Fold and Drop capabilities :.....................................................................................................108Other interesting Subfile Keywords:...................................................................................109Additional Recommended Reading Material......................................................................109

Chapter VIII: Arrays, Tables and Data structures.............................................110Arrays:.....................................................................................................................................110

Array Description :..............................................................................................................110Loading of an array:.................................................................................................................111

Compile time array:.............................................................................................................111Prerun time Array:..............................................................................................................112Run time array:....................................................................................................................113

Searching Arrays.....................................................................................................................115Searching an Array without an Index..................................................................................115Searching an Array with an Index.......................................................................................116

Specifying an Array in Calculations........................................................................................117Tables :.....................................................................................................................................119Data Structures:.......................................................................................................................119

Format of Data Structure Subfields in Storage:..................................................................120Data Structure Statement Specifications:............................................................................120Examples:............................................................................................................................121Multiple Occurrence Data Structure:...................................................................................122

Data Areas :.............................................................................................................................124Implicitly retrieved and written:..........................................................................................124Explicitly retrieved and written:..........................................................................................124

Data Structures For Exception/Error Control..........................................................................126File Information Data Structures (INFDS):........................................................................126Program Status Data Structure:..........................................................................................127

Chapter IX: RLU and Printer Files.....................................................................129Report Layout Utility (RLU)...................................................................................................129

Report Line..........................................................................................................................129Report Prototype..................................................................................................................129Printer File Keywords.........................................................................................................129Processing Printer Files in RPG Programs:.......................................................................132

Chapter X: Control Language.............................................................................133Functions..................................................................................................................................133Command Structure.................................................................................................................133

Positional Form...................................................................................................................134Keyword form......................................................................................................................135Both positional and Keyword form......................................................................................135Command Continuation.......................................................................................................137Variable naming syntax.......................................................................................................137Concatenation......................................................................................................................138

5 of 150

Page 6: RPG400 Course Material

Relational Expressions........................................................................................................138Logical Expressions.............................................................................................................138Substring expressions..........................................................................................................139Using variable in a CL program.........................................................................................139Using files in CL program...................................................................................................139File Operations....................................................................................................................140Error Handling....................................................................................................................140Assigning Values..................................................................................................................142Logical Operations..............................................................................................................142

Chapter XI: Open Query File Basics...................................................................143Open data Path(ODP) :............................................................................................................143QRYSELECT..........................................................................................................................144Steps involved in a typical OPNQRYF program:...................................................................145Example:..................................................................................................................................145

Chapter XII: Message Subfiles in RPG..............................................................147Message Subfiles.....................................................................................................................147

Steps Involved :....................................................................................................................147Example :.............................................................................................................................148

Appendix A : RPG Opcodes.................................................................................153Appendix B : AS/400 Data Limits........................................................................158Appendix C : RPG/400 Restrictions......................................................................159

6 of 150

Page 7: RPG400 Course Material

Chapter I :AS/400 Highlights

Introduction :

AS/400 is designed as an entire system ,taking into account all the layers that were added to systems over last 30 years as we discovered one after another while the computer industry matured. Current mature operating systems were originally batch processors , many times patched to accommodate interactive and database use with many faster ,roomier drives. The user sees these systems today through various and complicated interfaces and paths.

On the other hand , AS/400 design engineers created the layers of the onion from the outside in – the opposite of the design of older machines. First the functions that we all wanted, then user level interfaces that would make that function easy and accessible. Then the layers below those interfaces that would shield us from the intricacies of getting the function; finally a layered and queued system beneath the software in hardware(putting much software function of today into microcode). Paths among the layers were made standard and therefore movable and changeable.

Technology-Independent Machine Interface

The AS/400 is a typical in that it is defined by software, not by hardware. In other words, when a program presents instructions to the machine interface for execution, it "thinks" that the interface is the AS/400 hardware. But it is not! The instructions, presented to that interface, have to pass through a layer of microcode before they can be understood by the hardware itself. This design insulates application programs and their users from changing hardware characteristics through this comprehensive layer of microcode. When a different hardware technology is deployed, IBM rewrites sections of the microcode to absorb the fluctuations in hardware characteristics. As a result, the interface presented to the customer remains the same.

This interface is known as the Technology-Independent Machine Interface (or TIMI). The microcode layer is known as the System Licensed Internal Code (or SLIC). The brilliance of this design was dramatically illustrated when the AS/400 changed its processor technology from CISC (Complex Instruction Set Computing) processors to 64-bit RISC (Reduced Instruction Set Computing) processors in 1995. With any other system, the move from CISC to RISC would involve recompiling (and possibly some rewriting) of programs. Even then, the programs would run in 32-bit mode on the newer 64-bit hardware. This is not so with the AS/400, because of TIMI. Customers were able to save programs off their CISC AS/400s, restore them on their new RISC AS/400s, and the programs would run. Not only did they run, but they were fully 64-bit programs.

7 of 150

Page 8: RPG400 Course Material

As soon as they made this transition, customers had 64-bit application programs that ran on a 64-bit operating system containing a 64-bit relational database that fully exploited the 64-bit RISC hardware.

Operating System OS/400

One of the single most dramatic things about AS/400 is that its operating system, OS/400, is a single entity. This section describes the meaning of this concept.

Once you buy an AS/400, you do not have to continue shopping for system software components before it is ready to run your business. All of those software components, for relational database, comprehensive security, communications with a broad range of diverse systems, including Internet capabilities, and many more, are already there.

They are all fully integrated into OS/400 (AS/400 operating system). By "fully integrated", we mean fully tested, too. All those components, prerequisites for running business applications in the 1990s, work together and are fully tested together, so that OS/400 operates as a single entity.

An ordinary machine does not have this approach to its operating system design.

Single-Level Storage

Just as application programs on an AS/400 are unaware of underlying hardware characteristics because of the TIMI. They are also unaware of the characteristics of any storage devices on the AS/400, because of single-level storage.

As with TIMI, the concept of single-level storage means that the knowledge of the underlying characteristics of hardware devices (in this case, the hardware storage devices-- main storage and disk storage) reside in the SLIC. All of the storage is automatically managed by the system. Programs work with objects, and objects are accessed by name, never by address. No user intervention is ever needed to take full advantage of any storage technologies.

The AS/400's address size is vast.

8 of 150

Page 9: RPG400 Course Material

Single-level storage enables another extremely important AS/400 benefit--object persistence.. Object persistence means that the object continues to exist in the memory system forever. An ordinary machine requires that information be stored in a separate file system if the information is to be shared or if it is to be retained for a long time. Persistence of objects is extremely important for future support of object-oriented databases. Objects need to continue to exist even after their creator goes away. The AS/400 is uniquely positioned to exploit this characteristic of object persistence, where ordinary systems use a less-elegant mechanism that requires them to store their persistent objects in a separate file system, with all the attendant performance implications.

Logical Partitioning (LPAR)

As the performance of an enterprise class server grows, so does the requirement to divide that performance to run multiple workloads independently. Partitioning enterprise servers has become commonplace in the mainframe market since its introduction the mid-1980s. Typically, separate partitions are used for test releases of applications or to service multiple business units or companies from a single server.

Logical partitions (LPAR) enable multiple independent OS/400 instances or partitions in an n-way symmetric multiprocessing. Each partition requires its own processor(s), memory, disk(s), system console, with a CD-ROM and tape drive that can be allocated to each LPAR. With LPAR, you can address multiple system requirements in a single machine to achieve server consolidation, business unit consolidation, mixed production/test environments, integrated clusters, and more.

Objects

An object is a container. Everything the system uses--user and system data structures--is packaged in one of these containers. The objects are encapsulated, which means that you cannot see inside. Inseparable from an object is the list of valid ways in which that object can be used. All objects are structured with a common object header, and a type-dependent functional portion. Therefore, on the AS/400, instructions can only work on what they are supposed to work on. You cannot have data treated as executable code (so that the processor tries, for example, to execute someone's shoe-size), or executable code treated as data, (by having something written into the middle of it). Certain instructions apply to all objects, while other instructions work only on specific types of objects. It is not possible to misuse an object, unlike the situation that exists other systems without an object-based approach.

There are two important consequences of an object-based design. The first is that a system built around an object model supports machine independence. This means that technology changes can be made in the environment without affecting application programs. The second consequence is that an object-based design delivers a high level of system integrity.

Components of an object Name –Generic name

9 of 150

Page 10: RPG400 Course Material

Library- that which contains addressability to the object Type – attribute that defines the purpose of an object within the system. Each type has an associated set of commands that is used to process that object type. Attribute-An additional characteristic of an object within the object type. Owner-Name of the user who owns the object. Creation date /time. Save date /time. Restore date /time. Volume identifier for save. Free storage indication – Indication whether the object storage was freed when the object was saved. Size-Number of bytes allocated to the object in auxiliary storage.

Examples of ObjectsCMD Command

Basic form of high level instruction to the system

DEVD Device Description An information set describing the physical and logical attributes of a device connected to the system.

DTAARA Data area : A data store

DTAQ Data Queue

FILE File

JOBD Job desriptionInformation describing environment in which a job would be executed

JOBQ Job QueueQueue where the jobs wait for execution.

JRN Journal:Object which controls storing of application data that needs to be recovered in case of a system failure.

JRNRCV Journal Receiver:File in which application data that needs to be recovered in case of a system failure is stored. A journal receiver is always associated with a journal.

LIB LibraryUser defined place within the system where any particular group of objects reside.

MSGF Message FileA database file where messages are stored.

MSGQ Message QueueQueues where messages wait to be passed or displayed.

10 of 150

Page 11: RPG400 Course Material

OUTQ Output QueueQueue where the system output waits to be viewed printed or transferred

PGM Program

11 of 150

Page 12: RPG400 Course Material

AS/400 Processing Environment

What is a job?

A job is the basic unit of work on the AS/400.Every activity on the AS/400 is done as part of a job. Each job is a single , identifiable sequence of processing actions that represent a single use of the system.

Attributes of a job:Job number:The job number is a unique system generated sequential numberJob Name :Job name is any user defined name. For certain jobs, the system assigns a job

name which is usually the name of the corresponding job description.User Name:User name attributed with a job is the name of the user who initiated the job.

The combined usage of the job number, job name and user name uniquely identifies a job in the system.

Job Description:

A job description is a collection of parameters that control the job when it is started in the subsystem. The advantage of using a job description is that once it is defined you can use it anywhere just by referring to the job description name whenever you want to start job.

Subsystem

A subsystem is single predefined operating environment in which the system coordinates the work flow and resources. Subsystems are specific user defined job partitions of the CPU where various jobs may be executed. The system is shipped with a set of IBM supplied subsystems which may be modified if required. One subsystem may have more than one job active at a time.

Job Queues

Job Queues are streams where jobs wait for execution. Job queues are attached to specific subsystems. One subsystem may have more than one jobq attached to it.

Output Queues

Output queues are streams where output from the jobs wait to be processed. It is a place to hold the output spooled files created by jobs.

Type of Jobs

Interactive jobs:

12 of 150

Page 13: RPG400 Course Material

An interactive job starts when the user signs on to the machine and lasts until user signs off. A job is created by the system to interactively react to the users responses and thus is called an interactive job.

Batch jobs:A Job is called a batch job when a series of actions submitted to a job queue

for execution in one single job stream. Spooling job:

A spooling job can be for input or output.In an input spooling job ,a system program called a reader transfers job from the input device such as a diskette or database file.For output spooling , the job puts the output from a program into a spooled file , later the spooled file can be written to an external device such as a printer.

Autostart job:A autostart job is always associated with the subsystem , and whenever the

subsystem is started the autostart job is started as well.

Additional Recommended Reading Material :1.SC41-8078-01 AS/400 Work Management Guide

13 of 150

Page 14: RPG400 Course Material

AS/400 SecurityThe Security is unbreachable because it is not a layer added on top of an interface , which , after being unlocked provides complete access. Rather, it is a check built in every step the system takes for you (once again , with this system you only request work to be done for you , you do not actually do it yourself). It is built into both the hardware and the software and it has to do with function ,location, user type and type of use.

On the AS/400 all information is stored in objects. Access to that information is through hardware instructions that ensure object integrity . Any attempt to misuse an object detected, causing the system to terminate the instruction and signal an exception condition.

Security at object level:

Object ownership:All objects have owners. Initially , the user who creates the object is the owner. However,

the owner, the Security officer, or a user with Object existence rights can transfer ownership to another user.

Public or Private authority over an object:Object use can be authorized privately or publicly. ‘Private’ means to specific users;

‘Public’ means to all users. Looking at Security from the object outward:

The owner of the object has authority to do all things possible to it. *ALLOBJ authority can be granted to a user , which gives this user ‘ all things

possible’ authority. Now the grantee can further grant authority and revoke it as well, even from the original owner.

*PUBLIC authority reaches everybody and can be granted by the owner at some command level to all system users.

Security over libraries can be defined at these levels: *EXCLUDE – Users Can’t get it all(only the owner and security officer can use it) *USE – A user can DISPLAY the content of the library ,use commands to find

objects ,put the library in LIB list, and save the library. *ALL- Users have all the object authorities and all the data usage level authority on

the contents of this library on the library itself.

Object Authority:

Object authority is used to control access to an object including the ability to see an object description, control read and write access to an object, or control an object's existence.

*OBJMGT : provides the authority to specify the security (grant/revoke object authority), move or rename the object, and add members to database file.

14 of 150

Page 15: RPG400 Course Material

*OBJEXIST: provides the authority to control the object existence and ownership. The user with this authority can delete, save, and transfer ownership of the object.

*OBJOPR : provides the authority to look at the description of an object and use the object as determined by the data authority that the user has to the object.

Data Authority:

Data authority is the authority to access data contained in an object, for example records in a database file. This includes the ability to view, update, add, or delete records.

*READ :provides the authority to get the contents or an entry in an object or to run a program.

*ADD :provides the authority to add entries to an object.

*UPD :provides the authority to change the entries in an object.

*DLT :provides the authority to remove entries from an object.

Combinations of Object and Data Authorities

These are keywords, each representing predefined combination of object and data authorities. They reduce the time required to assign specific authorities to users.

*ALL allows the user to perform all authorized operations (object and data) on the object.

*CHANGE provides *OBJOPR authority and all data authority.

*USE provides *OBJOPR authority and data read authority.

*EXCLUDE authority prevents the user from accessing the object even if *PUBLIC is authorized.

In addition to these, users can create customized combinations of object and data authorities

Security Functions

Setting the security levels for the systemThe system can be set to various security levels. The system is shipped with a ‘minimum’ security level, which means that any user can sign on and use any data or programs on the system. If your system has more than just ‘minimum’ security officer controls, who has access to the system and its data.

15 of 150

Page 16: RPG400 Course Material

Security Levels

The AS/400 system allows to select the level of security needed to use on your system. The different levels provide varying degrees of security, which are as follows:

Level 10The system is not secured. No password is required to signon. No resource security is used, so all users can access and use all system resources.Level 20The system has limited security. A password is required to signon, but no resource security is used. All users can access and use all system resources.Level 30The system is designed to be fully secured. A password is required to signon.Resource security is used , which means that system resources are available to users depending on what objects they have authority to use and what special authorities they have.Level 40The system is designed to be fully secured, as it is for level 30.In addition, the system is protected from access by unsupported interfaces.

16 of 150

Page 17: RPG400 Course Material

Application Development Tools (ADT)

Program Development Manager (PDM)

Program Development Manager is a complete development tool which allows the programmer to perform all programming related activities under one single menu driven easy to use and comprehensive environment.

Functions of PDM PDM allows the user to work with the libraries and objects in terms of performing the following functions among others.

Create Change Display Delete Rename Move

Work with members namely Edit / Rename / Clear / Remove Find strings, that is to find a character or string in a source or data file. Define Commands to perform repetitive actions on objects from a list Call the other Application Tools mentioned Below :

Source Entry Utility (SEU)Screen Design Aid (SDA)Data File Utility (DFU)Report Layout Utility (RLU)

17 of 150

Page 18: RPG400 Course Material

Invoking PDMProgram Development Manager can be invoked in any one of the following ways :1. Take option ‘5’ for the programmers menu from the AS/400 main menu.Then take option ‘2’ for PDM from the programmer’s menu2. Enter command ‘STRPDM’ from any command entry line

AS/400 Programming Development Manager (PDM) Select one of the following: 1. Work with libraries 2. Work with objects 3. Work with members 9. Work with user-defined options Selection or command ===>______________________________________________________________________________ F3=Exit F4=Prompt F9=Retrieve F10=Command entry F12=Cancel F18=Change defaults (C) COPYRIGHT IBM CORP. 1981, 2000.

18 of 150

Page 19: RPG400 Course Material

3. Enter command ‘WRKLIBPDM” – Work with Libraries in PDM – from any command entry line to work with libraries

Work with Libraries Using PDM List type . . . . . . . *LIBL Type options, press Enter. 2=Change 3=Copy 5=Display 7=Rename 8=Display description 9=Save 10=Restore 12=Work with ... Opt Library Type Text - RBTSYSLIB *PROD-SYS ROBOT SYSTEM LIBRARY - QSYS *PROD-SYS SYSTEM LIBRARY - QSYS2 *PROD-SYS SYSTEM LIBRARY FOR CPI'S - QHLPSYS *PROD-SYS - QUSRSYS *PROD-SYS System Library for Users - SYSTEM *PROD-SYS EHQ System Software - XCOM2 *PROD-SYS CA-XCOM software library - QMQM *PROD-SYS MQSERIES FOR AS/400 - QSYS2924 *PROD-SYS More... Parameters or command ===> ______________________________________________________________________________ F3=Exit F4=Prompt F5=Refresh F6=Add to list F9=Retrieve F10=Command entry F23=More options F24=More keys

4. Enter command ‘WRKOBJPDM” – Work with objects in PDM – from any command entry line to work with objects Work with Objects Using PDM Library . . . . . TSTLIB Position to . . . . . . . . ________________ Position to type . . . . . ________________ Type options, press Enter. 2=Change 3=Copy 4=Delete 5=Display 7=Rename 8=Display description 9=Save 10=Restore 11=Move ... Opt Object Type Attribute Text - XMSGDTARFP *FILE PF-DTA MDL Message Physica - YABOABARFP *FILE PF-DTA yaboabarfp Physical fi - YABOABAXXP *FILE PF-DTA Contains YABOABARFP deleted model dat - YABOABA00L *FILE LF MDL Abo update (@@ABOABA) - YABOABA01L *FILE LF MDL Abo action rtv (@@ABO/@@CHC/@@ABO - YABOABA02L *FILE LF MDL Abo action rtv (@@ABO/@@ABOABA_P) - YABOABA03L *FILE LF MDL Abo action rtv (@@ABO/@@REFCND > - YABOABA04L *FILE LF MDL Abo update (@@ABO/@@ABOABA) More... Parameters or command ===>______________________________________________________________________________ F3=Exit F4=Prompt F5=Refresh F6=Create F9=Retrieve F10=Command entry F23=More options F24=More keys

5. Enter command ‘WRKMBRPDM” – Work with members in PDM – from any command entry line to work with members

19 of 150

Page 20: RPG400 Course Material

Work with Objects Using PDM Library . . . . . TSTLIB Position to . . . . . . . . ___________ Position to type . . . . . _____________ Type options, press Enter. 2=Change 3=Copy 4=Delete 5=Display 7=Rename 8=Display description 9=Save 10=Restore 11=Move ... Opt Object Type Attribute Text XMSGDTARFP *FILE PF-DTA MDL Message Physica YABOABARFP *FILE PF-DTA yaboabarfp Physical fi YABOABAXXP *FILE PF-DTA Contains YABOABARFP deleted model dat YABOABA00L *FILE LF MDL Abo update (@@ABOABA) YABOABA01L *FILE LF MDL Abo action rtv (@@ABO/@@CHC/@@ABO YABOABA02L *FILE LF MDL Abo action rtv (@@ABO/@@ABOABA_P) YABOABA03L *FILE LF MDL Abo action rtv (@@ABO/@@REFCND > YABOABA04L *FILE LF MDL Abo update (@@ABO/@@ABOABA) More... Parameters or command ===>______________________________________________________________________________ F3=Exit F4=Prompt F5=Refresh F6=Create F9=Retrieve

PDM is terminated by pressing EXIT (F3) function key

Source Entry Utility (SEU)

Source Entry Utility is a development tool that allows the entry, review and display of program source statements and date descriptions specification for various specification types.

Functions of SEUSEU function is allow the user to:

Create / add new members Revise existing members Browse / Copy the existing members

SEU can be invoked through one of the following methods:1. Select option ‘5’ from the programmers menu2. Select option ‘2’ from the Work with members display in PDM to browse through the source members3. Select option ‘5’ from the Work with members display in PDM to edit source members4. Enter command ‘STRSEU’ from any command entry line.If the command is Invoked without a qualified member name, a list of all the members in the file is displayed.

20 of 150

Page 21: RPG400 Course Material

Data File Utility (DFU)

Data File Utility (DFU) is a development tool that allows the entry, revision and browse of data records from the database files.

Functions of DFUDFU functions are to allow for the creation of applications for the manipulation of data records. These applications can then be executed to manipulate data records. Manipulation of data records includes adding or inserting new records and changing, deleting or displaying existing records

AS/400 security allows for the restriction of access to the selected files bound by the user Securiry.

Additional recommended reading Material:1. SC09-1338-02 SEU User’s Guide and Reference.2. SC09-1339-02 PDM User’s Guide and Reference.3. SC09-1340-02 SDA User’s Guide and Reference.4. SC09-1416-02 RLU User’s Guide and Reference.5. SC41-9614-03 AS/400 Query / 400 User’s Guide.

21 of 150

Page 22: RPG400 Course Material

Chapter II –Libraries

A Library is an AS/400 object that serves as a repository for other objects. It is not a parititioned data set but rather an index to other objects. The library can never become ‘full’ as it has no definite size. Generally a library can contain any set of objects grouped for a specific purpose.

Library CategoriesThe libraries can be categorised ac IBM supplied libraries, user-defined libraries .

IBM Supplied Libraries are: 1. QSYS Contains IBM supplied programs and data.This library cannot be deleted or renamed. This library is owned by system security officer.

2. QSYS36 Contains objects required to run software developed on the System/36.The software would then be executed in ‘System/38 mode’.

3. QSYS38 Contains objects required to run software developed on the System/38. The software would then be executed in ‘System/38 mode’

4. QGPL Contains IBM supplied objects for general use. This library is present in every library list unless explicitly removed.

5. QTEMP Created automatically for every job. The library hold temporary objects such as work files. This library can be accessed by the job that created it. This library would be deleted when the job is terminated.

6. QSRV Service engineer library.

7. QRCL Reclaim storage library .It is created when a Reclaim Storage command(RCLSTG) is executed and would contain objects that were purged by the command.

8. QRPG Report Program Generator library. It contains RPG compiler and the objects required to enter,edit and compile RPG programs.

22 of 150

Page 23: RPG400 Course Material

9. QCBL COBOL/400 library.It contains COBOL compiler and the objects required to enter, edit and compile COBOL/400 programs.

10. QIBU Interactive data base utilities library.

11. QINS Interactive workstation support library that contains all IBM supplied objects that are required to transfer data between AS/400 and PCs.

User-defined libraries These libraries are created by users for specific application and uses.User-defined library name may be use-defined alphanumeric name not more than 10 characters. Library names may not have embedded blanks and must not begin with a number.

Library List: It is a list of libraries associated with each job which defined the operational boundaries of a job. Each job has a default library list which may be modified if required.Each library list consists of four parts. They are: System library section - This section consists the libraries containing objects used by the system for regular processing functions. The number of libraries in this section cannot exceed 15. Product library section - This section contains libraries that are required to support high level languages and utilities other than QSYS. Current library section – This section contains the ‘current library’ as identified by the job. User library section – This section contains libraries required by system users and applications such as non-IBM application solutions.The number of libraries in this section cannot exceed 25.

Library commands:Common commands associated with libraries are: CRTLIB Create library DSPLIB Display library DLTLIB Delete library

Library List Commands:Common commands associated with library lists are:

23 of 150

Page 24: RPG400 Course Material

DSPLIBL Display library list ADDLIBLE Add library list entry RMVLIBLE Remove library list entry RPLLIBL Replace library list CHGCURLIB Change current library

Additional Recommended Reading Material1. GC41-9802-01 AS/400 System Concepts.

Chapter III: AS/400 Database

In AS/400, the data base is integrated into the operating system and is the licensed internal code of the AS/400 system. There is no requirement to install or maintain a separate database management product. Any program that wants to store or use data on the AS/400 system uses integrated database

24 of 150

Page 25: RPG400 Course Material

File Types:The different types of files that form AS/400 database ar

1. Database files are files (including distributed files) whose associated data

is stored permanently in the system.

i. Physical files

1. Data files

2. Source files

ii. Logical files

2. Device files are files that provide access to externally attached devices such as displays, printers, tapes, diskettes, and other systems that are attached by a communications line. The device files supported are:

– Display files, which provide access to display devices– Printer files, which describe the format of printed output– Tape files, which allow access to data files on tape devices– Diskette files, which provide access to data files on diskette devices– Intersystem communications function (OS/400-ICF) files, hereafter referred to

as ICF files, which allow a program on one system to communicate with a program on the same system or another system

3. Save files are files that are used to store saved data on disk (without requiring diskettes or tapes).

4. Distributed Data Management files (DDM files) are files that allow access to data files stored on remote systems.

Each file type has its own set of unique characteristics that determines how the file can be used and what capabilities it can provide. The concept of a file, however, is the same regardless of what type of file it is. When a file is used by a program, it is referred to by name, which identifies both the file description and, for some file types, the data itself. This information is designed to help you understand the common characteristics of all file types so you can use the files to their full capabilities.

Database Files:• The Object type is *file• It contains description of how input data is to be presented to programs from internal

storage and how output data is to be presented to internal storage from a program

Access paths:

Arrival Sequence Access Path :• It is based on the order in which the records arrive and are stored in the file

25 of 150

Page 26: RPG400 Course Material

• Sequentially, where each record is taken from the next sequential physical position in the file

• Directly by relative record number, where the record number is identified by its position from the start of the file

Keyed Sequence Access Path:• It is based on the contents of the key fields as defined in DDS• This type of access path is updated, whenever records are added or deleted.

Physical Files:

• A description of how data is to presented to or received from a program and how data is actually stored in the database

• A Physical file contains one record format and one or more members

Components of a Physical File• Object Header This contains the regular object information• Record Format Describes the format in which the records are stored• Access Path Describes the order in which records are to be retrieved • Data Member Contains data

Data Description Specification for a Physical File:• File Level entries (optional):

File level entries give the system information of the entire file including whether the key is unique

• Record Level entries : Give the system information about the specific record format in the file

• Field Level entries : The field names and field lengths are specified along with an optional text description for each field

• Key Field Level entries : The field names used as key fields specified

DDS Keywords:• File Level : Unique, LIFO, FIFO, FCFO, Ref• Record Level : Format, Text• Field Level : Alias, Reffld, Text, Edtcde, Datfmt, Datsep, Alwnull, Check(AB,

ME, MF), Cmp/Comp, ColHdg, Dft, Range, Timfmt, Timsep, Values• Key-field Level : Absval, Descend, Signed, Unsigned

Characteristics of a Physical File• Maximum no. of fields that can be defined in a PF is 8000• Maximum no. of members that a single PF can have is 32,766• Maximum size of a member in a PF is 32,766 bytes• Maximum length of a file name is 10 characters• Maximum length of a record format name is 10 characters• Maximum length of a field name is 10 characters• Maximum number of key fields in a PF is 200View of a Physical File:

26 of 150

Page 27: RPG400 Course Material

File Level UniqueRecord Level R RecfmtField Level Name 20

Age 10 P Phone 10 P 3

Key-Field Level k Name

Logical Files:

• Logical File is an AS/400 object of type *file and attribute LF• Used to arrange data from one or more physicals into different formats and sequences • Logical file does not contain any data, but provides ‘VIEWS’ of the data to satisfy end-

users’ needs • A logical file can contain up to 32 record formats and can obtain data from 2 to 32

physical filesComponents of a Logical File:

• Object Header This contains the regular object information• Record Format Describes the format in which the records are stored• Access Path Describes the order in which records are to be retrieved • Data Member Contains Data

Data Description Specification for a Logical File:• File Level entries (optional):

File level entries give the system information of the entire file including whether the key is unique

• Record Level entries : Give the system information about the specific record format in the file

• Join Level entries : Give the system information about physical files used in JOIN Logical File (Not applicable for Non-Join Logical File)

• Field Level entries : The field names and field lengths are specified along with an optional text

description for each field• Key Field Level entries :

The field names used as key fields specified• Select / Omit Level entries :

Give the system information about, which records are to be returned to the program when processing the file

DDS Keywords:• File Level : Unique, LIFO, FIFO, Jdftval(JLF)• Record Level : Jfile (Join File), Pfile (Physical file), Text• Join Level : Jdupseq, JFld, Join• Field Level : Alias, Reffld, Edtcde, Datfmt, Datsep,

Check(AB, ME, MF), Cmp/Comp, ColHdg, Dft, Range, Timfmt, Timsep, Values, JRef

27 of 150

Page 28: RPG400 Course Material

• Key-field Level : Absval, Descend, Signed, Unsigned• Select/Omit Level : Comp, Range, Values, All

View of a Logical File:Record Level R PFRecfmt1 PFILE(PF1)Key-field Level K Cust#

Types Of Logical Files

• Non - Join Logical Files• Join Logical Files

Join Logical File

• Join logical files are READ only files and may not be used in UPDATE or DELETE processing

• Support only Inner and Left Outer Joins. Outer Join processing is not supported• They may refer 2 to 32 physical files• Any key field specified must be included in the primary file• Select / Omit criteria may be specified for any field in a Join Logical File Data Description Specification for Join Logical Files:

• File Level entries• Join Level entries• Record Level entries• Field Level entries• Key Field Level entries• Select and Omit Field Level entries

View of a Join Logical File: R Joinrcd JFILE(PF1 PF2) J JOIN( 1 2 )

JFLD( ENO ENUM ) Enum JREF(1) Ename JREF(1) Dept JREF(2) K Enum S Enum comp GT 1010

Types of Join Logical File:There are 3 types of Logical Files

1. Natural Join or Inner Join : When this type of a JLF is read only the matching records of both the files appear

28 of 150

Page 29: RPG400 Course Material

2. Left Outer Join : All the records from the primary file appear. Missing secondary records (records for which no match is found) are filled with default values. This is enforced by using JDFTVAL keyword

3. Self Join: Joining a file to itself

Non - Join Logical File:

• A Non-Join logical file can either be a simple logical file which contains only one record format or a multiple format logical file which contains more than one record format

• Non-Join logical files can be used for READ, WRITE and UPDATE processing• Can join a maximum of 32 Physical files •Data Description Specification for Non-Join Logical Files:

• File Level entries• Record Level entries• Field Level entries• Key Field Level entries• Select and Omit Field Level entries

Repeat steps 2 through 5 for each record format in the file

View of a Non-Join Logical File:Record Level R PFRecfmt1 PFILE(PF1)Field level Cust#Key-field Level K Cust#Record Level R PFRecfmt2 PFILE(PF2)Field level Cust#Key-field Level K Cust#

Field Reference Files:• A physical file that contains no data, but only description of fields.• It is used as a reference for the field descriptions of other files

Importance of using Field Reference Files

It enforces the naming convention• Reduces programmer’s work load (define once, use often)• It defines in one place all data elements used in the application for all users

Naming Conventions• The file name, record format name, field name cannot be more than 10 character’s• The first character should be alphabetic• Field names should be unique in a record format

29 of 150

Page 30: RPG400 Course Material

• Record format names and member names should be unique in a file• File names should be unique in a library

Additional Recommended Reading Material

1. SC41-9659-02 AS/400 Database Guide

2. SC41-9658-02 AS/400 Data Management Guide

30 of 150

Page 31: RPG400 Course Material

Chapter IV: Data Description Specification (DDS)

Data Description Specifications(DDS) defines all attributes of a file and which are codedin a system-defined format. These definitions or specifications can be maintained externally and independent of programs or other dependent files. These statements are entered into a system-defined format as a source file which is created or compiled as a file.Data records are then written into or retrieved from this file using certain ApplicationDevelopment Tools or though use-defined application programs.DDS are coded and entered into a system-defined format known as ‘A’ specifications.Each file is coded as a separate source member.’A’ specifications are used to code the following types of files.The positions and entries are unique and may differ for the different files.

Physical files.

Logical files

Display (or workstation) files and

Printer files

Defining Physical FilesThe Data Description Specifications(DDS) for Physical Files are defined in dataspecifications in the following layout:Positions Name Entry Explanation

1-5 Sequence number

None This is an optional column and may be used to identify, mark or tag source statements.

6 Form type ‘A’ Denotes ‘A’ Specification

7 Comment ‘*’ Denotes a comment line. Comments may be entered betweenpositions 8 and 80.

8-16 Reserved Blank This position Is not used for physical files and must be blank.

17 Type of Name ‘R’‘ ‘‘K’

Record format name.Field name.key field name.

19-28 Name Record name or field name or key field name.

29 Reference R Denotes that a definition and attributes of thenamed field are to be referenced from a previously defined field.

31 of 150

Page 32: RPG400 Course Material

Positions Name Entry Explanation

30-34 Length Length of the field.The following are the valid lengths for various types of fields.Character 1 to 32766 Hexadecimal1 to 32766Binary 1 to 9Numeric 1 to 31

35 Data Type PSBFAHLTZ

Packed decimalZoned decimalBinaryFloating pointCharacterHexadecimalDateTimeTimestamp.

36-37 Decimal position

Number of decimalpositions

38 Usage ‘B’

‘ ‘

Both input and outputDefaults to B

39-44 Location This column is reserved and is not used by physical files.

45-80 Keywords.

Components of DDS

DDS definitions are a serious of statement that are entered as source statements. These statements may be entered in to the following levels of definitions.

File level keywords are entered at the file qualify the named file and are applicable to all the record and field definition that follow. Record format level keywords are entered at the record format level qualify the named record format and are applicable to all the field definitions contained within the record format. Join level keywords are used to specify parameters that are used to join one or more files in to a single record format. These keywords are valid only in join logical files. Field level keywords are used to qualify the named field. Key field level keywords are used to qualify the key or the access sequence of a file. For example, UNIQUE can be specified to prevent existence of duplicate key values in a file. Select/Omit level keywords are used to specify rules for the selection of records from a physical file, these keywords are valid only in logical files.

32 of 150

Page 33: RPG400 Course Material

Naming ConventionsThe normal rule for naming of files, record formats and fields is a 10 character alphanumeric value which does not contain embedded blanks and does not start with a numeric value. However, some high level languages like RPG/400 supports only 8 character file and record format names and 6 character field names.

Physical File Keywords

Keywords used in physical files are vided into 4 parts. They are:File level KeywordsRecord level KeywordsField level KeywordsKey-field level Keywords

There are in all over 35 keywords associated with physical files.These keywords are used to provide further qualification to the file, record format, field or key field.Some of the more commonly used keywords are:

File Level Keywords

FCFO First Changed First OutWhen duplicate key exists in a file this keyword is used to specify that the record that was changed earliest is to be retrieved.

FIFO First In First OutWhen duplicate key exists in a file this keyword is used to specify that the record that was written earliest is to be retrieved.

LIFO Last In First OutWhen duplicate key exists in a file this keyword is used to specify that the record that was written most recently is to be retrieved.

REF ReferenceUsed to indicate the name of another file from which field references wherever indicated are to be retrieved.

UNIQUE Unique KeyUsed to indicate that records with duplicate key values will not be allowed in this file.

Record Level Keywords

TEXT TextUsed to assign descriptive text for the record format.

Field Level Keywords

ALIAS Alias NameUsed to indicate the alias name for the named field.

ALWNULL Allow Null value

33 of 150

Page 34: RPG400 Course Material

Used to indicate that the field may be written with NULL value (blanks for character fields and zeroes for numeric fields)

CHECK Check valuesUsed to provide certain validity rules for the named field.The values associated with this keyword are as follows:

AB Allow blanksME Mandatory EntryMF Mandatory FullM10 Modulus 10 validationM10F Modulus 10 validation(IBM variation)M11 Modulus 11 validationM11F Modulus 11 validation(IBM variation)

Example, CHECK(ME) CMP/COMP Compare Value

Used to provide validation to specify that the named field must contain value specified in this parameter. Example, COMP(*EQ ‘A’)

COLHDG Column HeadingUsed to provide descriptive text about the named field. This text is used when the field is used in certain application development tools such as Data File Utility(DFU) and Query. Up to three strings of 20 characters each can be specified.

DATFMT Date FormatUsed to define the format (namely one of either, YY/MM/DD or MM/DD/YY or DD/MM/YY) in which date is to be stored in the named field.

DATSEP Date separatorUsed to identify the character used to separate the elements of a date.

DFT Default ValueUsed to nominate a default value when the record is written.

EDTCDE Edit CodeUsed to identify a system-supplied editing rule for the named field. Rules could include zero suppression, zero balance, sign etc.

RANGE RangeUsed to specify a range of values that are allowed to be input in to the named field.

REFFLD Referenced FieldUsed to reference a field from an earlier referenced file whose length and attributes are to be attached to the named field.

REFFLD(FLDA)REFFLD(RECFMT01/FLDA)REFFLD(RECFMT01/FLDA FILEA)REFFLD(RECFMT01/FLDA *LIBL/FILEA)REFFLD(RECFMT01/FLDA LIBA/FILEA) TEXT Text

Used to assign descriptive text to the named field to be used in all future references of the named field. Example, TEXT(‘Customer code’).

TIMFMT Time Format

34 of 150

Page 35: RPG400 Course Material

Used to define the format in which time is to be stored in the named field. TIMSEP Time Separator

Used to identify the character to be used to separate the elements namely hour,minute and second of time.

VALUES ValuesUsed to assign one or more values that are allowed as valid input in to the named field. Example, VALUES(‘A’, ‘B’, ‘C’, ‘D’, ‘E’).

Key Field Level Key words

ABSVAL Absolute ValueUsed to indicate that when retrieving records from the named file, the sign of the key field is to be ignored and only the absolute value of the field is to be used for purposes of ordering sequences.

DESCEND Descending SequenceUsed to specify an ordering sequencing for the retrieval of records from the named file.when retrieving records from named file, the records would be sequenced in the descending order of the named key field.

SIGNED SignedUsed to specify that the sign of the named key-field is to be considered for purposes of ordering sequence when retrieving records from the named file.

35 of 150

Page 36: RPG400 Course Material

Defining Logical FilesThe Data Description Specifications(DDS) for Logical Files are defined in data specification in the following.

Positions Name Entry Explanation1-5 Sequence

NumberNone This is an optional column and may be

used to identify mark or tag source statements.

6 Form Type ‘A’ Denotes ‘A’ specification7 Comment ‘*’ Denotes a comment line .Comments may

be entered between positions 8 and 80.8-16 Conditioning Blank This position is not used for logical files

and must be blank17 Type of Name ‘R’

J ‘ ‘ ‘K’ ‘S’ ‘O’

Record format nameJoin SpecificationField nameKey field NameSelect CriteriaOmit Criteria

18 Reserved Blank This position is not used for logical files and must be blank

19-28 Name Record name or field name or key field name

29 Reference R Denotes that a definition and attributes of the named filed are to be referenced from a previously defined field.

30-34 Length Length of the field the following are the valid lengths for various types of fields.

Character 1 to 32766Hexadecimal 1 to 32776Binary 1 to 9Numeric 1 to 31

35 Data Types PS

BFAH

Packed decimalZoned decimalBinaryFloating pointCharacterHexadecimalDate

36 of 150

Page 37: RPG400 Course Material

Positions Name Entry ExplanationLTZ

TimeTimestamp

36-37 Decimal Position

Number of decimal positions.

38 Usage ‘B’ Both input and outputDefault to B

39-44 Location Blank Thos column is reserved and is not used by logical files.

45-80 Keywords

Logical file Keywords

Keywords used in logical files are divided into four parts, namely , File level keywords Record level keywords Field level keywords Key-field keywords There are in all over 45 keywords associated with logical files .These keywords are used to provide further qualification to the file , record format, field or key fields. Some of the more commonly used keywords are explained in the subsequent section.

File Level Keywords

DYNSLT Dynamic SelectUsed to instruct that selection of records according to the criteria specified in the file must be maintained dynamically as and when records are written into or retrieved from the database file that is pointed to by the logical file.

FCFO First Changed First outWhen duplicate key exists in a file this keyword is used to specify that the record that was changed earliest is to be retrieved. FIFO First In First OutWhen duplicate key exists in a file this keyword is used to specify that the record that was written earliest is to be retrieved. LIFO Last In First OutWhen duplicate key exists in a file this keyword is used to specify that the record that was written most recently is to be retrieved. UNIQUE Unique KeyUse to indicate that records with duplicate key value will not allowed in this file.

37 of 150

Page 38: RPG400 Course Material

Record Level Keywords

PFILE Physical FileUsed to name the physical file that is being pointed to by the named logical file.This keyword is mandatory for every logical file definition. TEXT TextUsed to assign descriptive text for the record format.

Field Level Keywords ALIAS Alias NameUsed to indicate the alias name for the named field . CHECK Check ValuesUsed to provide certain validity for the named field. The value associated with this keyword are as follows:AB Allow BlanksME Mandatory EntryMF Mandatory FullM10 Modulus 10 ValidationM10F Modulus 10 Validation(IBM variation)M11 Modulus 11 ValidationM11F Modulus 11 Validation(IBM variation) Example,CHECK (ME).

CMP/COMP Compare ValueUsed to provide validation to specify that named field must contain value specified in this parameter.Example,COMP(*EQ’A’) COHDG Column HeadingUsed to provide descriptive text about the named field.This text is used when the field is used in a certain application development tools such as Data File Utility(DFU)and QUERY.Upto three strings of 20 characters each can be specified . DATFMT Date FormatUsed to define the format (namely one of either ,YY/MM/DD or MM/DD/YY or DD/MM/YY)in which date is to be stored in the named field. DATSEP Date SeparatorUsed to identify the character used to separate the elements of a date. EDTCDE Edit CodeUsed to identify a system-supplied editing rule for the named field.Rules could include zero suppression,zero balance ,sign,etc. TEXT TextUsed to assign descriptive text to the named filed to be used in all future references of the named filed.Example ,TEXT(‘Customer Code’). TIMFMT Time FormatUsed to define the format in which time is to be stored in the named field. TIMSEP Time SeparatorUsed to identify the character to be used to separate the elements namely hour,minute and second of time.

38 of 150

Page 39: RPG400 Course Material

VALUES ValuesUsed to assign one or more values that are allowed as valid input into the named field.Example,VALUES(‘A’’B’’C’”D’’E’).

Key Field Level Keywords ABSVAL Absolute ValueUsed to indicate that when retrieving records from the named file the sign of the key-field is to be ignored and only the absolute value of the field is to be used for purpose of ordering sequences. ALL All

Used in conjunction with Select and Omit criteria specification to indicate that all records not fulfilling the Select or Omit criteria must be selected or omitted as the case may be.

DESCEND Descending SequenceUsed to specify an ordering sequence for the retrieval of records from the named file.When retrieving records from the named file,the records would be sequenced in descending order of the named key-field. SIGNED SignedUsed to specify that the sign of the named key-field is to be considered for purposes of ordering sequence when retrieving records from the named file. UNSIGNED Unsigned Used to specify that the sign of the named key-field is to be ignored for purposes of ordering sequence when retrieving records from the named file.

Join Logical Files

A join logical is a logical file which contains definitions required to join two or more different files based on certain user-defined join conditions.

The first file being joinng is called the ‘Primary file’ while the other are called ‘Secondary files’.The primary file and atleast one of the secondary files must be a physical file.

When accessing a join file record, the system internally reads a record from the primary file and picks up the corresponding record from the secondary file based on the user-defined join criteria and then presents the combined data to the accessing program in one consolidated record.

If required, when specifying the primary file and secondary file ,only certain fields from either file may be selected for join file record format rather than all the fields from both the files. But all the fields indicated in join criteria must be selected .

Special consideration* You cannot change a physical file using a join logical file.* You can specify only one record format in join logical file.* Commitment control cannot be used with join logical files.

39 of 150

Page 40: RPG400 Course Material

Join Level Keywords

The keywords used in join logical files are: JFILE Join File Identifies the names of the two files being joined.This keyword is specified at the record level. JFLD Join FieldUsed to name the fields that are to be used for purposes of joining the primary file and secondary file.Join fileds must have the same attributes.This keyword is specified at the record level. JOIN JoinIdentifies the names of the two files being joined.This keyword is specified at the join level. JREF Join Reference File Identifies the file from which the named fields is to be retrieved from.This keyword is specified at the field –level.

40 of 150

Page 41: RPG400 Course Material

Examples of database files in DDS:

Example of a field reference file:

This example defines all of the fields used in an application and refers to fields only within the field reference file itself. The following keywords are important in the example: COLHDGEDTCDE(Z)REFFLDREFSHIFTTEXT

The following field reference file (MLGREFP) describes all fields used by any program in the application. The other files use the fields in this file.

Figure 1. DDS for a Field Reference File

00010A** FLDREF MLGREFP MAILING LIST FIELD REFERENCE FILE00020A (1)R MLGREFR TEXT('Mailing List Field Reference')00030A ACTNUM 5 0 COLHDG('Account' 'Number')00040A EDTCDE(Z)00050A ACTTYP 1 0 COLHDG('Acct' 'Type')00060A TEXT('Acct Type 1=Bus 2=Gvt +00070A 3=Org 4=Sch 5=Pvt 9=Oth')00080A NAME 18 COLHDG('Name')00090A REFSHIFT(X)(4)00100A ADDR R (2) (2)REFFLD(NAME)00110A COLHDG('Address')(3)00120A CITY R (2) (2)REFFLD(NAME)00130A COLHDG('City') (3)00140A STATE 2 COLHDG('State')00150A ZIP 5 0 COLHDG('ZIP' 'Code')00160A EDTCDE(X)00170A BATNUM 6 0 COLHDG('Batch' 'Number')00180A EDTCDE(Z)00190A TRNTYP 1 COLHDG('Trans' 'Type')00200A TEXT('Trans Type A=Add +00210A C=Change D=Delete')00220A XACTNM R REFFLD(ACTNUM)00230A XACTTTP R REFFLD(ACTTYP)00240A XNAME R REFFLD(NAME)00250A XADDR R REFFLD(ADDR)00260A XCITY R REFFLD(CITY)00270A XSTATE R REFFLD(STATE)00280A XZIP R REFFLD(ZIP)00290A TRNNUM 5 0 COLHDG('Transaction' 'Number')00300A EDTCDE(Z)00310A MLGLK1 3 0 COLHDG('Lock' 'Control')00320A TEXT('Control Number Used for +00330A record locking')

Legend:

41 of 150

Page 42: RPG400 Course Material

(1) Like all physical files, a field reference file has only one record format. The R in position 17 specifies that MLGREFR is the record format name. (2) The Rs in position 29 and REFFLD in positions 45 through 80 specify that the fields ADDR and CITY are to have the same attributes as NAME. (3) Specifying COLHDG for ADDR and CITY overrides the COLHDG attribute for NAME, which otherwise would have been in effect. (4) Specifying REFSHIFT for NAME will cause the keyboard shift specified (X) to be used when this field (NAME) is referred to in a display file.

Example of a physical file with a new record format:

The REF keyword is important in the following example. This file has one record format. The names of all fields in the record format are specified. This example uses fields in a reference file (REF keyword) and uses a keyed-sequence access path.

The following physical file (called CUSMSTP for customer master physical file) describes the fields physically present in the database.

Figure 2. DDS for a Physical File

00010A*00020A* SAMPLE PHYSICAL FILE(CUSMSTP)00030A*00040A (1) REF(MLGREFP)00050A (2) R CUSMST TEXT('Customer Master Record')00060A ACTNUM R (3)00070A NAME R (3)00080A ADDR R (3)00090A CITY R (3)00100A STATE R (3)00110A ZIP R (3)00120A (4) SEARCH 10 000130A (4) CRDLMT 8 200140A (5) K ACTNUM

Legend:

(1) At the file level, the REF keyword refers the OS/400 program to the physical file MLGREFP, which is a field reference file for this database. (2) At the record level, R in position 17 specifies that CUSMST is the record format name of the record in this file. (There can only be one record format in a physical file.) (3) At the field level, Rs in position 29 specify that the attributes of fields of the same name in the REF file are to be used as attributes of these fields. (4) The fields SEARCH and CRDLMT are not defined in MLGREFP; therefore, their field attributes are specified here. (5) At the key field level, K in position 17 specifies that ACTNUM is the key field for the file.

42 of 150

Page 43: RPG400 Course Material

Example of a logical file specifying multiple formats and new keys:

The PFILE keyword is important in the following example. The example uses new field specifications and provides two record formats. Each record format provides a different view of the associated physical file and uses a key different from the associated physical file.

Figure 3. DDS for a Logical File Specifying New Keys

00010A*00020A* SAMPLE LOGICAL FILE00030A00040A R CUSMST1 (1)PFILE(CUSMSTP)00050A ACTNUM00060A NAME00070A STATE00080A LASTNAME I (3)SST(NAME 8 10)00090A (2) K ACTNUM00100A*00110A R CUSMST2 (1)PFILE(CUSMSTP)00120A ACTNUM00130A NAME00140A ZIP00150A K *NONE00160A (2) K NAME

Legend:

(1) The two record formats (CUSMST1 and CUSMST2) in this logical file are based on the same physical file (CUSMSTP). (2) Record format CUSMST1 has a key different from record format CUSMST2, providing the application program with a different sequence of the same records. (3) The LASTNAME field is a substring of the field NAME. The usage I in position 38 must be specified since this is not a join logical file.

Example of a logical file specifying a new record format:

The UNIQUE keyword is important in the following example. The example specifies a record format different from the associated physical file.

The following logical file (called CUSMSTL2 for customer master logical file two) uses some of the fields in the physical file CUSMSTP. Another logical file could name all fields, name fields in other physical files as well, concatenate fields, change the order of fields, rename fields, or choose different key fields. In this logical file, the programmer merely omitted some fields from the physical file.

Figure 4. DDS for a Logical File

43 of 150

Page 44: RPG400 Course Material

00010A*00020A* SAMPLE LOGICAL FILE (CUSMSTL2)00030A*00040A (1)UNIQUE00050A R CUSREC (2)PFILE(CUSMSTP)00060A TEXT('Logical File Master Record')00070A ACTNUM (3)00080A NAME (3)00090A ADDR (3)00100A (4)K ACTNUM

Legend:

(1) The UNIQUE keyword specifies that records with duplicate keys are not allowed within a member of this logical file. (2) The keyword PFILE (required for logical files) specifies CUSMSTP. (3) The field names do not have R specified in position 29 as they would in physical files or in any device file. (4) As in CUSMSTP, the field ACTNUM is treated as a key field.

Example of a join logical file:

The following join logical file joins three physical files (PF1, PF2, and PF3) so that an application program can get name, address, and salary information in one input operation, even though the information is stored in three different physical files. The following keywords are important in the example:

JFILE JFLD JOIN JREF

Figure 5. DDS for a Join Logical File

00010A (1)R JOINREC (2) JFILE(PF1 PF2 PF3)00020A J JOIN(PF1 PF2)00030A (3) JFLD(NAME NAME)00040A J JOIN(PF2 PF3)00050A JFLD(NAME NAME)00060A (4) NAME (5) JREF(1)00070A (4) ADDR00080A (4) PHONE00090A (4) SALARY A

Legend:

(1) R identifies the record format. There can be only one record format in a join logical file. (2) The JFILE keyword specifies that PF1, PF2, and PF3 are the physical files on which this join logical file is based. Because it is specified first, PF1 is the primary file. There are two secondary files: PF2 and PF3.

44 of 150

Page 45: RPG400 Course Material

(3) J identifies the join specifications. With two secondary files in this join logical file, there must be two join specifications. Each join specification defines how a pair of files is to be joined, as follows: JOIN is required when more than two physical files are being joined, and it identifies which two files are being joined in this join specification. In the first join specification, PF1 and PF2 are joined. In the second join specification, PF2 and PF3 are joined.

Note: Secondary files can be joined to either the primary file or to another secondary file. In this example, PF2 in the second JOIN keyword could be PF1; there would be no difference in the order of records supplied to the program or in performance.

JFLD identifies which fields are used to link together records from the physical files being joined. In the first join specification, NAME from PF1 links with NAME from PF2. In the second join specification, NAME from PF2 links with NAME from PF3.

(4) The field names show which fields are presented to the program. At least one field name is required. (5) The JREF keyword identifies which physical file to search for the field name; in this example, NAME from PF1 is used. Note the use of the direct file number: JREF(1) indicates to use the first file on the JFILE keyword, which is PF1.

DDM FilesThe DDM files is used as a reference file by AS/400 program to access files located on any target system in the AS/400 network.

DDM files may be created through two methods, either by the work with DDM files (WRKDDMF) command, then form the list display press F6 to create a DDM file or by the Create DDM file (CRTDDMF) command directly on the source system.

Additional Recommended Reading Material1. SC41-9659-02 AS/400 : Database Guide2. SC41-9620-02 AS/400:DDS Reference

45 of 150

Page 46: RPG400 Course Material

Chapter V: SDA and Display Files

Screen Design Aid(SDA):This is a development tool is to aid in the creation of user interfaces on the AS/400.This tool allows a programmer to "paint" screens and menus used by a program from within a simple editor, defining input and output fields and special text attributes. These screens may then be called from an application program, allowing the program to have all the features of the AS/400 user interface without direct programming of the appearance of the interface.

SDA can be invoked by either selecting option ‘9’ from Programmer’s menu or through typing the command ‘STRSDA’ from AS/400 command entry line. AS/400 Screen Design Aid (SDA) Select one of the following: 1. Design screens 2. Design menus 3. Test display files

Selection or command ===> F1=Help F3=Exit F4=Prompt F9=Retrieve F12=Cancel (C) COPYRIGHT IBM CORP. 1981, 2000.

Screen Designing:The following function keys can be used while designing your image:

F3=Exit

46 of 150

Page 47: RPG400 Course Material

Terminates screen design session.The Exit Design Image work screen displays appears where there is a choice to save the work , and return to the Work with Display records menu.

F4=PromptShows Work with Fields display.

F6=ConditionShows the Condition Work Screen display.

F9=Select additional recordsSelects additional records to display on the Design image work screen.

F10=DatabaseShows the display for selecting Database Files display.

F11=Non-display selected fieldsToggle between two fields lists that are displayed on the bottom row of the work screen.

F12=CancelSave the current work and return to the Work with Display records display.(Note:Anything that have been typed since last pressed enter is not processed.)

F14=RulerPlace a vertical and horizontal ruler on the Design Image work screen to position the cursor.The ruler does not interfere with the data.Press F14 to remove the ruler .Defining fields on the ruler may cause results that cannot be predicted.

F15=Subfile Prompt.This function will work only when a subfile exists.Press F15 display prompt on the bottome row of the Design Image work screen that allows changing the subfile line(SFLLIN) and subfile page(SFLPAG) sizes that were in effect for the current record being defined.

F17=PrintPrint the current contents of the Design Image work screen.

F18=TabMoves the cursor to the attribute position of the next field.

F19=Back TabMoves the cursor to the attribute position of the previous field.

F20=Reverse Image ConstantsSwitch the reverse imaging of constants on and off.This reverse imaging is temporary and does not affect the compiled image.

47 of 150

Page 48: RPG400 Course Material

Use F20 to determine the starting and ending points of the constants. Constants which have the underline attribute (but not the reverse image and highlight attributes) will not be displayed in reverse image. Constants that are not currently displayed will be highlighted and will appear in reverse image.

F21=Display additional records.

Displays the additional records with the primary record. Press F21 again to display only the primary record. Use this function key to determine which fields on the display belong to the primary record. Only the fields of the primary record can be changed.

Adding fields.

To add a user defined field, type + followed by I (input), O(output), or B(both) for alphabetic fields, or followed by 3(input), 6(output), or 9(both) for numeric fields and press Enter. To add a floating point field, add a numeric field followed by E (single-precision) or D(double-precision) and press Enter. Indicate the length of a field by the number of characters following +, or by the length specified in brackets after the first characters.

Adding constants

To add a new constant or change an existing constant1. Type a constant. A blank character ends the constant.2. Type constants with single quotation marks to define separate constants for each

character string(word) that is followed by a blank.3. Surround a character string with single quotation marks to define single constant.4. Surround several constants with single quotation marks to redefine them as one

constant.5. Use a double quotation mark to end one constant and start a new constant while

taking up only one position.

Adding fields from a database file

The fields selected from the database file appear on the bottom row of the Design Image work screen. Move fields from the bottom line to your display by typing & followed by the field number, in multiple mode, and the column heading position and pressing Enter. he fields begin in the position where you type &.

48 of 150

Page 49: RPG400 Course Material

Moving, Copying and Shifting fields

Reposition fields on the screen by using their attribute position.(Note: The attribute position is the space directly in front of the field. Press F19 to go to the attribute position of the previous field. Press F18 to go to the attribute position of the next field.)

Choose from the from the following methods and press Enter.

Centering a field

Type AC in the attribute position of the field to move the field to the center of the same row.

Moving a field - , =

Type – in the attribute position of the field and type = where you want the field to appear.

Copying a field - , ==

Type – in the attribute position of the field and type == where you want a copy of the field to appear.

Moving a block of fields -, -, =Type – in the upper left corner of the block of fields. Type – in the lower right corner of the block of fields so the – is one character beyond the longest field in the block. Type = where you want the group of fields to appear.

Copying a block of fields -, - ,==Type – in the upper left corner of the block of fields. Type – in the lower right corner of the block of fields so the – is one character beyond the longest field in the block. Type == where you want the group of fields to appear.

Shifting a field <<<, >>>Type <<< in the position preceding the field (attribute position of the fields), or type >>> after the field (over the ending attribute byte), to shift the field left or right as far as the signs extend. You may type any number of > or <, and you can shift more than one field at a time in the work screen.

Date and Time keywords.

Type *DATE or *TIME to define special constants on the display where the current session date and system time will be automatically substituted.

User and system keywords

49 of 150

Page 50: RPG400 Course Material

Type *USER or *SYSNAME to define special constants on the display where the user name and the system name will be automatically substituted.

Display Files:

The following types of record formats can be defined in display files:

Single Record Formats are normal record formats with a fixed number of variables and literals defined in them

Subfile Record Formats are record formats that define a particular format but which allows the processing of multiple records of the same definition.

Subfile Control Record Formats are record formats that control the processing of a related Subfile record format.

Display File Keywords

There are over 130 keywords associated with display files. These keywords are used to provide additional qualification to the display file at various levels. Display file keywords my be divided into the following groups.

File Level keywords, they are used at the file levels and are common to all the record formats in that file.

Record Level keywords, they are used at a particular record level and applicable to all the constants and fields in the given record format.

Field Level keywords apply to a particular field in a record format.

Some of the more commonly used keywords are detailed below:

File Level Keywords

ALTHELP Alternate Help KeyUsed to assign an alternate command key as the help key.

ALTPAGEDOWN Alternate Page Down KeyUsed to assign an alternate command key as the page down key

50 of 150

Page 51: RPG400 Course Material

ALTPAGEUP Alternate Page Up KeyUsed to assign an alternate command key as the page up key

ALWGPH Allow GraphicsUsed to specify that graphic characters could be generated and displayed in the named display file. This keyword however is valid only for workstations that support graphic displays such as the IBM 5292.

CAnn Common Attention KeysUsed to assign the usage of indicators to be associated with command keys.

CFnn Common Function KeysUsed to assign the usage of indicators to be associated with command function keys.Command Function Keys differ from command attention keys in that the data is transferred between screens only with the usage of command attention keys.

CHGINPFDT Change input defaultDefined at the file level so that the field level defaults can be overridden with the user specified attributes.

DSPSIZ Display sizeUsed to assign the display size of the work station display.

HELP Help keyUsed to assign an indicator for the Help key so that the program may recognize its usage.

HOME Home keyUsed to assign an indicator for the Home key so that the program may recognize its usage.

MSGLOC Message LocationUsed to identify a line of display where the messages may be displayed.

PRINT Print keyUsed to enable the facility of taking the screen prints and to identify a printer file name into which any screen prints are to be directed

REF Referenced FileUsed to identify a file from which all the field references are to be derived from.

ROLLUP Rollup KeyUsed to specify an indicator that is to be associated with the Rollup key. This indicator can then be used to trigger program action for the Rollup function.

ROLLDOWN Rolldown Key

51 of 150

Page 52: RPG400 Course Material

Used to specify an indicator that is to be associated with the Rolldown key. This indicator can then be used to trigger program action for the Rolldown function.

Record Level Keywords

ALARM AlarmUsed to specify that the work station alarm is to be sounded when the named record format is output

ALWGPH Allow GraphicsUsed to specify that graphic characters could be generated and displayed in the named display file. This keyword however is valid only for workstations that support graphic displays such as the IBM 5292.

ASSUME AssumeUsed to indicate that named record format is to be assumed to be displayed by the previous program, used in association with the KEEP keyword in the calling program thisKeyword overlay the named record format over the previous display

BLINK BlinkUsed to indicate that named record format is to blink when displayed.

CHANGE ChangeUsed to specify an indicator which is to be set one when any of the input fields in the named record format is modified by the work station user.

CHGINPDFT Change input defaultDefined at the record level so that field level defaults can be overridden with the user specified attributes.

CSRLOC Cursor LocationUsed to position the cursor in a specified row-column position when the screen is displayed.

ERASE EraseThis keyword is used to erase a record in a specified row-column position when the screen is displayed.

ERASEINP Erase InputUsed to erase input fields from the named record format before the next output operation on the display file.

ERRMSG Error Message

52 of 150

Page 53: RPG400 Course Material

Used to specify the text to be displayed as an error message upon occurrence of an error condition.

ERRMSGID Error Message IdUsed to identify a message identity from a named message file to be displayed as a errorMessage upon the occurrence of an error condition

HLPCMDKEY Help Command KeyUsed to specify an indicator to be associated with the Help Key for the named record format.

HOME Home KeyUsed to assign an indicator for the Home key so that the program may recognize its usage.

KEEP Keep DisplayUsed to retain the display of the named record format even after the termination of the program so that the next program in the invocation stack may still be able to display the screen. This keyword to be used in the display file of the calling program in association with ASSUME keyword to be used in the display file of the called program.

OVERLAY OverlayUsed to retain the display of the format already displayed when the named record format is to be displayed.

PRINT Print KeyUsed to identify a printer file name into which any screen prints are to be directed

PROTECT ProtectUsed to identify that all the input capable fields in the named format are to be input inhibited.

PUTOVER Put overUsed to indicate that when used in association with OVRDTA or OVRATR keywords at the field level, only those screen data that have been changed in an input operation need be referred when the record format is output again.

Field Level Keywords

ALIAS AliasUsed to assign an alias name to a field.

CHANGE Change Used to specify an indicator which is to be set on when any of the input fields in the named record format is modified by the work station user.

53 of 150

Page 54: RPG400 Course Material

CHGINPDF Change input defaultDefined at the field level so that field defaults can be overridden with the user specified attributes.

CHECK CheckUsed to specify a set of validation rules such as

ME Mandatory Entry MF Mandatory Fill RB Right justified with blanks RZ Right justified with zeros

CMP, COMP CompareUsed to specify a literal value against which any input value to the field is validated on an input operation

COLOR ColorUsed to assign a color to a field or constant when it is displayed. Attribute values are

GRN Green WHT White RED Red TRQ Turquoise YLW Yellows PNK Pink BLU Blue

DATE DateUsed to specify that the system date is to be displayed in the specified position

DFT, DFTVAL Default valueUsed to assign a default value to a field to be displayed during an output operation

DLTCHK Delete validity checkingUsed to specify that any validity checking specified in the definition of the referenced field is to be ignored for the named field

DLTEDT Delete EditingUsed to specify that any editing rules specified in the definition of the referenced field is to be ignored for the named field.

DSPATR Display attributeUsed to nominate a display attribute to be attached to the named field during an output operation. Valid values are

54 of 150

Page 55: RPG400 Course Material

BL Blink CS Column separators HI High-light

ND Non – display PC Position Cursor PR Protect RI Reverse Image UL Underline

EDTCDE Edit codeUsed to specify an editing rule for numeric variables. Edit codes govern such parameters as zero balances, suppression of the leading zeros, commas, negative sign and credit balance. Edit coded can also be used to separate dates, month and year components of dates.

EDTWRD Edit wordUsed to specify the user defined editing rules for both alphabetic and numeric fields.

OVRATR Override attributesUsed in association with the PUTOVR keyword at the record level to indicate that only if the attributes of the named variable or literal has changed should data be sent to the screen in the next output operation.

RANGE RangeUsed to specify a range of values that are valid input values for the named variable

REFFLD Referenced field nameUsed to specify the name of a previously defined field from the file indicated as the referenced file at the file level.

SYSNAME System nameUsed to indicate that the system name is to be displayed in the specific row-column position at the next output operation

TEXT TextUsed to attach descriptive text for the named variable to be used when viewing or printing the display file field definitions.

TIME TimeUsed to indicate that the system is to be displayed in the specific row-column position upon the next operation to the screen

USER User nameUsed to indicate that the work station user name is to be displayed in the specific row-column position upon the next output operation to the screen.

55 of 150

Page 56: RPG400 Course Material

VALUES Valid valuesUsed to specify a set of valid values that can be allowed as input into the named variable during an output operation.

56 of 150

Page 57: RPG400 Course Material

Chapter VI: RPG/400

RPG/400 Language ConceptsRPG stands for ‘Report Program Generator’. RPG a high level language was originally designed to be a semi-automated tool for producing reports. However, with the continuous developmental efforts, currently RPG /400 is fully functional , highly sophisticated structured language that allows for performing a wide variety of tasks required in performing heavy-duty, high-volumes transaction processing in commercial applications.

The earliest version of RPG is RPG II .This is fully structured pre set logic cycle that is governed by certain system-defined rules for processing. This cycle assumes that standard set of instructions are performed which includes

Reading a file designed to be a primary file If end of file, print the end of file totals and control values Check for various level breaks and if so do the necessary processing and printing of

control breaks and totals Perform details line processing

The actual processing steps involved in the RPG logic cycle is detailed in the following chart. Refer to Appendix B for RPG cycle charts.

RPG III Procedural Programming RPG III is the next version of RPG that was introduced in the IBM System/30.Unlike RPG II this version is not a system defined logic cycle but rather a fully user controlled application language. All the tasks that were automatically performed in RPG II has to be deliberately performed by the user. While this might seem a little tedious ,the advantages and the flexibility provided in the full user control are commendable.

RPG/400

RPG/400 is the current version of RPG available on the AS/400.RPG/400 is the natural language on the AS/400.Certain aspects of the OS/400 lend themselves for easy application of RPG/400 as a language .Benchmark tests have proved that COBOL/400 application have a performance degradation of about 20% over RPG/400 applications.

The following are the main differences between RPG II and RPG/400.

57 of 150

Page 58: RPG400 Course Material

1. RPG/400 allows for the use of externally described files.

2. RPG/400 supports character string operations.

3. RPG/400 supports sub file initialization for data structure elements.

4. RPG/400 allows indentation of IF-ELSE and DO statements in source.

5. RPG/400 allows the use of figurative named constants.

6. RPG/400 supports exception and error handling.

7. RPG/400 is ideal for use of structured programming language.

RPG/400 Specifications

RPG/400 program consist of seven specifications. Each specification may include one or more statements. It is not necessary that all these specification be included in each program. However ,the specifications must necessarily follow the sequence in which they are listed there under. The specifications that form a RPG/400 program are:

H Control Specification F File Specification E Extension Specification

L Line counter Specification

I Input Specification

C Calculation Specification

O Output Specification

Details of the seven RPG specifications are as follows:

58 of 150

Page 59: RPG400 Course Material

H CONTROL SPECIFICATION

This is used to provide information about program generation and execution .It is included in a program , Control specification must be the first specification in the program. Only one control specification must be entered in a program .

F FILE SPECIFICATION

This is used to identify all the files that are required to be used by a program. Each file should be defined in a separate specification line. One program can use a maximum of 50 files of which upto 8 files can be printer files.

E EXTENSION SPECIFICATION

This is used by the program to describe all the record address files, tables and arrays . A maximum of 200 tables and arrays can be used in a program .

L LINE COUNTER SPECIFICATION

This is used by a program to indicate the length of form and the number of lines per page for every program described printer file..

I INPUT SPECIFICATION

This is used by program to define the various types of records within a file, the sequence of the various types of records within a file, the fields within a record and the data written within a field. For program described files ,the input specification define the filed layout of the file.Input specification is also used to define sub-file, data structure and the data areas.

C CALCULATION SPECIFICATION

This is used in a program to indicate the operations that are to be performed on data within a program.

O OUTPUT SPECIFICATION

This is used in a program to define the record the record layout of a program described output file .The output specification are optional for externally defined files.

RPG/400 Operation Codes (OPCODES):RPG Operation codes or Opcodes are commands which allow the program to perform various calculation and operations. There are in all over 80 opcodes used in RPG/400.These opcodes can be classified into the following broad categories. Some of the opcodes may be listed under more than one category due to their functionality. The opcodeClassification are :

Arithmetic Operations

59 of 150

Page 60: RPG400 Course Material

Move Operations Compare Operations Declarative Operations Initialization Operations String Operations Subroutine Operations Indicator Operations Structured Programming Operations File Operations Information Operations Message Operations BIT Operations Test Operations Calling Operations Branching Operations Array Operations DataArea Operations Commitment Control Operations

Arithmetic Operations

Arithmetic operations are those basic operations that are performed on numeric variables to arrive at calculated values. The following are the opcodes that relate to arithmetic operations in RPG/400 .All arithmetic operations are valid only when performed on numeric variables.

ADD (Add Statement)

Factor 1 Code Factor 2 Result Field Indicators

HI LO EQAddend ADD Addend Sum + - Z

Add two variables or constants to arrive at a sum to be store in a third variable Example: ADD 1 RECNO ADD EHWRK CURHRS OVRTM ADD REGHRS TOTPAY

Z-ADD (Zeroise and add)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Addend Z-ADD Addend Sum + - Z

Initialize a variable to zeros and add a second variable to the first

60 of 150

Page 61: RPG400 Course Material

Example: Z-ADD FIELDA FIELDB Z-ADD 1 FIELDA Z-ADD *ZEROS FIELDA

SUB (Subtract statement)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Minuend SUB Subtrahend Difference + - Z

Subtract the value of one variable from a third variable

Example FIELDA SUB FIELDB FIELDC SUB FIELDA FILEDB SUB 10 FIELDB 10 SUB 3 FIELDA

Z-SUB (Zeroise and subtract)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Minuend Z-SUB Subtrahend Difference + - Z

Initialize a variable to zeros and subtract a second variable from the first .The result of this operation would make the value of the first variable negative. This variable is used to make the value of a variable negative.Example: Z-SUB FIELDA FIELDB Z-SUB 1 FIELDA Z-SUB *ZEROS FIELDAThis statement is the same as specifying Z-ADD *ZEROS FIELDA

MULT (Multiply)

Multiply two variables and store the product in a third variable

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Multiplicand

MULT Multiplier Product + - Z

Example FIELDA MULT FIELDB FIELDC

61 of 150

Page 62: RPG400 Course Material

5 MULT FIELDA FIELDB FIELDA MULT 5 FIELDB 3 MULT 5 FIELDA MULT FIELDA FIELDB MULT *ZEROS FIELDB

DIV (Divide)

Divide a variable or constant by a second variable or constant and store the result in a third variable.

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Dividend DIV Divisor Quotient + - Z

Example: FIELDA DIV FIELDB FIELDC 5 DIV FIELDA FIELDB FIELDA DIV 5 FIELDB 5 DIV 3 FIELDA

MVR (Move remainder)

This opcode is valid only when immediately following an divide (DIV)operation.This operation stores the remainder from the previous operation is a variable .The result of a divide operation if followd immediately by a move remainder(MVR)operation would be in whole numbers.

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

MVR Remainder + - Z

Example:

MVR FIELDA

SQRT (Square root)

The operation calculates the square root of a variable and stores it in a second variable.Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ SQRT Value Root

Example

SQRT FIELDA FIELDB

62 of 150

Page 63: RPG400 Course Material

Move Operations:

MOVE (Move)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

MOVE Source field

Target Field + - ZB

Moves the contents of a variable or constant into a second variable. This operation is right-justified. Hence if a longer variable is moved into a shorter variable ,the left most characters(and in cases of numeric variables, significant digit )would be truncated.Example: MOVE FIELDA FIELDB MOVE ‘ABCDE’ FIELDC MOVE ‘12345’ FIELDD MOVE ‘1’ FIELDE

MOVEL (Move left)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

MOVE Source field

Target Field + - ZB

Moves the contents of a variable or a constant into a second variable .This operation is left-justified .Hence if a longer variable is moved into a shorter variables , the right-most characters would be truncated.Example MOVEL FIELDA FIELDB MOVEL ‘ABCDE’ FIELDC MOVEL 12345 FIELDD MOVEL ‘1’ *IN25

Compare Operations

The compare operations are:

ANDxx (And) COMP (Compare) CABxx (Compare and Branch) CASxx (Conditionally Invoke Subroutine) DOUxx (Do Until) DOWxx (Do While) IFxx (If) ORxx (Or) WHxx (When True Then Select)

In the ANDxx, CABxx, CASxx, DOUxx, DOWxx, IFxx, ORxx, and WHxx operations,

63 of 150

Page 64: RPG400 Course Material

xx can be:

xx Meaning GT Factor 1 is greater than factor 2. LT Factor 1 is less than factor 2. EQ Factor 1 is equal to factor 2. NE Factor 1 is not equal to factor 2. GE Factor 1 is greater than or equal to factor 2. LE Factor 1 is less than or equal to factor 2. Blanks Unconditional processing (CASxx or CABxx).

IFxx (If condition)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparand IFxx Comparand

Compare the value of one variable or literal against the value of second variable or literal to determine the course of action. The step/s taken as a result of this comparison must be marked with either an END operation or a ENDIF operation.Example:

If FLDA equals FLDB, the calculation after the IFEQ operationC* is processed. If FLDA does not equal FLDB, the program branches to the operation immediately following the ENDIF. FLDA IFEQ FLDB IF EQUAL : : : ENDIF CABxx (Compare and branch)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparand CABxx Comparand Label HI LO EQ

Compare the value of one variable or literal against the value of a second variable or literal to decide to branch away to another part of the program logic rather than execute the next statement following the compare and branch (CAB)operation.Example: FIELDA CABxx FIELDB TAG01 ‘ABCDE’ CABxx FIELDC TAG01 FIELDC CABxx ‘ABCDE’ TAG01 10 CABxx FIELDD TAG01 FIELDD CABxx 10 TAG01

64 of 150

Page 65: RPG400 Course Material

*IN25 CABxx ‘1’ TAG01

CASxx (Compare and execute subroutine)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparand CASxx Comparand SubroutineName

HI LO EQ

Compare the value of one variable or literal against the value of a second variable or literal to decide to execute a subroutine. Control then passes to the named subroutine and after completion of execution of the subroutine control returns to the statement immediately following the compare and execute CAS statement .Every CAS or group of CAS statement must be named with a END or ENDCS operation.

FIELDA CASxx FIELDB SUB01 ‘ABCDE’ CASxx FIELDC SUB01 FIELDC CASxx ‘ABCDE’ SUB01 10 CASxx FIELDD SUB01 FIELDD CASxx 10 SUB01 *IN25 CASxx ‘1’ SUB01

CAS SUBR03

DOUxx (Do until)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparand DOUxx Comparand

Perform the operation listed in a DO loop that is marked with an END or an ENDDO operation repetitively until the condition specified in then DO condition is satisfied.The loop would be performed at least once since the condition is checked only in the END or ENDDO operationExample: FIELDA DOUxx FIELDB ‘ABCDE’ DOUxx FIELDC FIELDC DOUxx ‘ABCDE’ 10 DOUxx FIELDD FIELDD DOUxx 10 *IN25 DOUxx ‘1’

DOWxx (Do while)

Factor 1 Code Factor 2 Result Field Indicators

65 of 150

Page 66: RPG400 Course Material

HI LO EQ Comparand DOWxx Comparand

Perform the operation listed in a DO loop that is marked with an END or an ENDDO operation repetitively while the condition specified in the DO ststement is satisfied .The loop would not be performed if on the first instance itself the condition is not satisfied.Example: FIELDA DOWxx FIELDB ‘ABCDE’ DOWxx FIELDC FIELDC DOWxx ‘ABCDE’ 10 DOWxx FIELDD FIELDD DOWxx 10 *IN25 DOWxx ‘1’

WHxx (When)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparand WHxx Comparand

A when condition is used to check for and process a group of conditions under a select group.A select group always starts with a SELEC statement and ends with an END or an ENDSL ststement.Example:

SELEC FIELDA WHxx FIELDB

: : ENDSL

COMP (Compare)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ Comparand COMP Comparand HI LO EQ

Compare the value of a variable or literal against the value of a second variable or literal and appropriately switch on one of the resulting indicators.

‘HI’ indicator is switched on i.e the value of the indicator becomes ‘1’if factor one is greater than factor two. ‘LO’ indicator is switched on i.e the value of the indicator becomes ‘1’if factor one is less than factor two. ‘EQ’ indicator is switched on i.e the value of the indicator becomes ‘1’if factor one is equals factor two.

66 of 150

Page 67: RPG400 Course Material

FIELDA COMP FIELDB ‘ABCDE’ COMP FIELDC FIELDC COMP ‘ABCDE’ 1 COMP FIELDD FIELDD COMP 1 2 COMP 5

Declarative Operations

PLIST ( Parameter list)

A parameter list is used to declare one or more variable that are required to be passé to another program that is being called from within the named program .A parameter list may be declared anywhere within the calculation specification specifications or a program and need not necessarily be placed in a logical position.

Refer ’Calling Operations’ for more information..

PARM (Parameter)

A parameter statement identifies individual variable that form a parameter list. A PARM statement must necessarily be placed immediately following a PLIST statement or another PARM statement. The sequence in which the PARM statements are listed would be the sequence in which these variables are passed to the calling program.

Refer to ’Calling Operations’ for more information..

KFLD (Key Field)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

KFLD Key field

The KFLD operation is a declarative operation that indicates that a field is part of a search argument identified by a KLIST name.

KLIST (Key list)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

List Name KLIST

67 of 150

Page 68: RPG400 Course Material

The KLIST operation is a declarative operation that gives a name to a list of KFLDs. This list can be used as a search argument to retrieve records from files that have a composite key.Example

KLABC KLIST KFLD FILEDA KFLD FILEDB KFLD FILEDC

DEFN (Definition)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*LIKE DEFN Referenced field

Defined field

*NAMVAR DEFN External data area

Internal Program area

Depending on the factor 1 entry, the declarative DEFN operation can do either of the following: Define a field based on the attributes (length and decimal positions) of another field. Define a field as a data area.

Example:*LIKE DEFN FIELDA FIELDB*NAMVAR DEFN FMINDT AREA01

TAG(Tag)

A tag statement is used to identify the address of a branching operation such as CABxx or GOTO.

TAG01 TAG

Initialization Operations

CLEAR (Clear)

Factor 1 Code Factor 2 Result Field Indicators

68 of 150

Page 69: RPG400 Course Material

HI LO EQ*NOKEY CLEAR Structure

or Variable

The CLEAR operation sets elements in a structure (record format, data structure, array, or table) or a variable (field, subfield, or indicator), to zero, blank or '0', depending on field type (numeric, character, or indicator). It allows you to clear structures on a global basis, as well as element by element, during run time.

Factor 1 must be blank unless factor 2 contains a DISK record format name; in which case, it can contain *NOKEY to indicate that all fields except key fields are to be cleared.*...1....+....2....+....3....+....4....+....5....+....6....+....7... I....................................PFromTo++DField+L1M1FrPlMnZr... I* I* In the following example, CLEAR sets all subfields in the data I* structure DS1 to their defaults, CHAR to blank, NUM to zero. IDS1 DS I 2 50 NUM I 20 30 CHAR *...1....+....2....+....3....+....4....+....5....+....6....+....7... CL0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++ C* C CLEARDS1

RESET (Reset)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*NOKEY RESET Structure or Variable

The RESET operation sets elements in a structure (record format, data structure, array, or table), or a variable (field, subfield, or indicator) to its initial value. The initial value for a variable is the value the variable had at the end of the *INIT operation of the program. This value can be set using data structure initialization, or you can use the initialization subroutine to assign an initial value to the structure or variable.

String Operations

CAT (Concatenate Two Character Strings)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Source string 1 CAT (p) Source string 2: number Target string

69 of 150

Page 70: RPG400 Course Material

of Blanks

The CAT operation concatenates the character string specified in factor 2 to the endof the character string specified in factor 1 and places it in the result field. If nofactor 1 is specified, factor 2 is concatenated to the end of the result field string.

For example, if you have:C 'bMIKEbb' CAT 'bbSMITHb':1 Namethe value of the result field after this statement is executed is: 'bMIKEbbbSMITHb'

CHECK (Check Characters)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQComparator string

CHECK Base string:start

Left-position _ ER FD

The CHECK operation verifies that each character in the base string (factor 2) isamong the characters indicated in the comparator string (factor 1). Verifying begins at the leftmost character of factor 2 and continues character by character, from left to right.

The operation stops checking when it finds the first incorrect character or when theend of the base string is encountered. If no incorrect characters are found, theresult field is set to zero.

If the result field is an array, the operation continues checking after the first incorrect character is found for as many occurrences as there are elements in the array.If there are more array elements than incorrect characters, all of the remaining elements are set to zeros.

Example\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\ Because factor 1 is a blank, CHECK indicates the positionC\ of the first nonblank character. If STRING contains 'bbbthe',C\ NUM will contain the value 4.C\C ' ' CHECKSTRING NUM 20

\...1....+....2....+....3....+....4....+....5....+....6....+....7...I..............Namedconstant+++++++++C.........Fldnme......... ....I\I\ The following example checks that FIELD contains only the lettersI\ A to J. As a result, ARRAY=(136000) after the CHECK operation.I\ Indicator 90 turns on.I\I 'ABCDEFGHIJ' C LETTER\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C MOVE'1A=BC*' FIELD 6C LETTER CHECKFIELD ARRAY 90

70 of 150

Page 71: RPG400 Course Material

C\C\ In the following example, because FIELD contains only theC\ letters A to J, ARRAY=(000000). Indicator 90 turns off.C\C MOVE 'FGFGFG' FIELD 6C LETTER CHECKFIELD ARRAY 90

CHEKR (Check Reverse)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Comparator string

CHEKR Base string:start

Right-position _ ER FD

The CHEKR operation verifies that each character in the base string (factor 2) isamong the characters indicated in the comparator string (factor 1). Verifying beginsat the rightmost character of factor 2 and continues character by character, fromright to left.

SCAN (Scan Character String)

Factor 1 Code Factor 2 Result Field

Indicators HI LO EQ

Comparator string:Length

SCAN Base string:start

Left Most Position

_ ER FD

The SCAN operation scans a character string (base string) contained in factor 2 for asubstring (compare string) contained in factor 1. The scan begins at a specifiedlocation contained in factor 2 and continues for the length of the compare stringwhich is specified in factor 1.

\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\ The SCAN operation finds the substring 'ABC' starting inC\ position 3 in factor 2; 3 is placed in the result field.C\ Indicator 90 is set on because the string is found. BecauseC\ no starting position is specified, the default of 1 is used.C 'ABC' SCAN 'XCABCD' RESULT 90

XLATE (Translate)

Factor 1 Code Factor 2 Result Field

Indicators HI LO EQ

From:To XLATE String:start Target String

__ ER __

71 of 150

Page 72: RPG400 Course Material

Characters in the source string (factor 2) are translated according to the From andTo strings (both in factor 1) and put into a receiver field (result field). Source char-acters with a match in the From string are translated to corresponding characters inthe To string. XLATE starts translating the source at the location specified in factor2 and continues character by character, from left to right.

\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\ The following translates the blank in NUMBER to '-'. The resultC\ in RESULT will be '999-9999'.C\C MOVE '999.9999'NUMBER 8C ' ':'-' XLATE NUMBER RESULT 8\...1....+....2....+....3....+....4....+....5....+....6....+....7...I..............Namedconstant+++++++++C.........Fldnme.............I\I\ In the following example, all values in STRING are translated toI\ uppercase. As a result, RESULT='RPG DEP'.I\I 'ABCDEFGHIJKLMNOPQRS- C UPI 'TUVWXYZ'I 'abcdefghijklmnopqrs- C LOI 'tuvwxyz'C\CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C MOVE ‘RpG Dep' STRING 7C LO:UP XLATESTRING RESULT 90C\C\ In the following example all values in the string are translatedC\ to lowercase. As a result, RESULT='rpg dep'.C\C MOVE 'RpG Dep' STRING 7C UP:LO XLATE STRING RESULT 90

SUBST (Substring)Factor 1 Code Factor 2 Result

Field Indicators HI LO EQ

Length to extract SUBST Base string:start

Target string

__ER __

The SUBST operation returns a substring from factor 2, starting at the location speci-fied in factor 2 for the length specified in factor 1, and places this substring in theresult field. If factor 1 is not specified, the length of the string from the start posi-tion is used.

\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\ The SUBST operation extracts the substring from factor 2 startingC\ at position 3 for a length of 2. The value 'CD' is placed in theC\ result field RESULT. Indicator 90 is not set on because no errorC\ occurred.C Z-ADD 3 T 20C MOVEL'ABCDEF' STRING 10C 2 SUBSTSTRING:T RESULT 90

72 of 150

Page 73: RPG400 Course Material

Subroutine Operations

CASxx (Compare and execute subroutine)

Compare the value of one variable or literal against the value of a second variable or literal to decide to execute a subroutine. Control then passes to the named subroutine and after completion of execution of the subroutine, control returns to the statement immediately following the compare and execute (CAS) statement. Every CAS or group of CAS statements must be marked with an END operation of an ENDCS operation. The ‘xx’ may be one of the relational operator

LT Less ThanLE Less than or Equal toEQ Equal toNE Not Equal toGT Greater ThanGE Greater than or Equal to

See ‘ Compare operations’ for more information

EXSR(Execute Subroutine)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

EXSR Subroutine name

Execute a named subroutine. Control passes to the named subroutine and upon completion of the execution of the subroutine which is indicated with an end subroutine operation (ENDSR) control returns t the statement immediately following the execute subroutine statement.

BEGSR(Begin Subroutine)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQSubroutine name

BEGSR

Begin execution of a subroutine. This is the first statement in a subroutine and continues till the end subroutine statement. A second subroutine can be executed from a subroutine although a subroutine cannot be executed recursively.

SUBR01 BEGSR

73 of 150

Page 74: RPG400 Course Material

ENDSR(End Subroutine)

Marks the end of a subroutine. After the end subroutine statement, control returns the statement immediately following the Execute subroutine EXSR or the compare and execute subroutine (CASxx) statement from which the named subroutine was executed.

ENDSRTAG99 ENDSR

Indicator Operations

SETON (Set on indicator)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ SETON ON ON ON

Sets on indicator to value ‘1’.

SETON 25SETON 25 26 27SETON 25 27SETON 27SETON 25 27

SETOF (Set off indicator)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ SETOF ON ON ON

Sets on indicator to value ‘0’.

SETOF 25SETOF 25 26 27SETOF 25 27SETOF 27SETOF 25 27

Structured Programming Operations

74 of 150

Page 75: RPG400 Course Material

The operations IFxx, DOUxx, DOWxx, CASxx and WHxx which were described earlier under compare operations also form part of structured programming operation.

ORxx (Or condition)Factor 1 Code Factor 2 Result

Field Indicators HI LO EQ

Comparand ORxx Comparand

The OR statement is always used in conjunction with an IFxx, DOUxx orDOWxx statement to provide additional qualification to the first statement. The OR statement would be executed only if the condition specified in the original statement is not satisfied.

Example:

FIELDA ORxx FIELDB‘ABCDE’ ORxx FIELDCFIELDC ORxx ‘ABCDE’10 ORxx FIELDDFIELDD ORxx 10*IN25 ORxx ‘1’

ANDxx (And condition)Factor 1 Code Factor 2 Result

Field Indicators HI LO EQ

Comparand ANDxx Comparand

The AND condition is always used in conjunction with a n IFxx, DOUxx orDOWxx statement to provide additional qualification to the first statement. The AND statement is executed in conjunction with the first statement, ie., only if both the first statement and the AND statement conditions are both fulfilled, the conditioned statements are executed.Example:

FIELDA ANDxx FIELDB‘ABCDE’ ANDxx FIELDCFIELDC ANDxx ‘ABCDE’10 ANDxx FIELDDFIELDD ANDxx 10*IN25 ANDxx ‘1’

ELSE (Else)

The else condition is optionally used with a IFxx statement. If the condition specified in the IFxx statement is not fulfilled, then the else condition would be checked. The statements till the END or ENDIF statement would be executed.

75 of 150

Page 76: RPG400 Course Material

END (End)

The end statement marks the end of a group of statements that were executed by one of either IFxx, DOUxx, or DOWxx statements.

ENDyy (End Condition)

The ENDyy statement marks the end of a specific group of statements that were executed under one of the following. Here ‘yy’ may be any one of

CS CASxx

DO DODOUxxDOWxx

IF IFxxSL SELEC

DO (Do Iteration)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Starting value

DO Limit value Index value

The DO operation begins a group of operations and indicates the number of times the group will be processed. To indicate the number of times the group of operations is to be processed, specify an index field, a starting value, and a limit value. An associated ENDDO statement marks the end of the group.Example:C*C* The DO group can be processed 10 times. The DO group stopsC* running when the index value in field X is greater thanC* the limit value (20) in factor 2 . C* The starting value of 2 is specified in factor 1 of the DOC* operation, and the incrementing value of 2 is specified inC* factor 2 of the ENDDO operation.C*C 2 DO 20 X 30 DO 10 TIMESC :C :C :C ENDDO 2

76 of 150

Page 77: RPG400 Course Material

SELEC (Select)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ SELEC

The select group conditionally processes one of several alternative sequences of operations. It consists of:

o A SELEC statemento Zero or more WHxx groupso An optional OTHER groupo ENDSL or END statement.

After the SELEC operation, control passes to the statement following the first WHxx condition that is satisfied. All statements are then executed until the next WHxx operation. Control passes to the ENDSL statement (only one WHxx is executed). If no WHxx condition is satisfied and an OTHER operation is specified, control passes to the statement following the OTHER operation. If no WHxx condition is satisfied and no OTHER operation is specified, control transfers to the statement following the ENDSL operation of the select group.

OTHER (Other)

Traps all conditions that were not satisfied within a SELEC group of conditions. This statement is the equivalent of the ELSE statement in a IFxx condition.

ITER (Iterate)

Forcibly branch to the end of a DO, DOUxx or a DOWxx condition bypassing all other statements in the DO group. Control is thus passed to the next iteration of the DO processing loop.

LEAVE (Leave)

Force terminate a loop processing, control would then pass to the statement immediately following the END or ENDyy statement is the case may be.

77 of 150

Page 78: RPG400 Course Material

File Operations

File Specification Combinations:

Spec File Name

File Type

File Designation

File Format

Record AddressType

Device RecordAddition

User Control

Input Mode: Opcodes can be performed : READ, READE, REDPE, READP, SETLL, SETGT, CHAIN,(OPEN, CLOSE)

F I F E K DISK (UC)

Input Mode: Opcodes can be performed : WRITE, READ, REDPE, READE, READP, SETLL, SETGT,CHAIN, (OPEN, CLOSE)

F I F E K DISK A (UC)

Update Mode : Opcodes can be performed : READ, READE, REDPE, READP, SETLL, SETGT, CHAIN,UPDAT, DELET( OPEN, CLOSE)

F U F E K DISK (UC)

Update Mode : Opcodes can be performed : WRITE, UPDAT, DELET, READ, READE, REDPE, READP,SETLL, SETGT, CHAIN, (OPEN, CLOSE)

F U F E K DISK A (UC)

Output Mode: WRITE, (OPEN, CLOSE)

F O K A (UC)

OPEN (Open File for Processing)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

OPEN File Name __ ER __

Opens a named file. This operation need be done only for those files that were specified as ‘User control’ in the file specifications. If ‘User control’ was not specified, RPG takes care of opening files upon program invocation.

CLOSE (Close Files)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

CLOSE File Name __ ER __

The explicit CLOSE operation closes one or more files or devices and disconnects them from the program. The file cannot be used again in the program unless you specify an explicit OPEN for that file. A CLOSE operation to an already closed file does not produce an error.Example:\...1....+....2....+....3....+....4....+....5....+....6....+....7...FFilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U..FEXCPTN O E DISK UCFFILEX I E DISK\...1....+....2....+....3....+....4....+....5....+....6....+....7...

78 of 150

Page 79: RPG400 Course Material

CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\C 97N98 OPEN EXCPTN 99 99=NO SUCCESSC 97N98N99 WRITEERRECC\C\C CLOSEFILEX

SETLL (Set Lower Limits)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Search argument/*HIVAL/*LOVAL

SETLL File Name NR ER EQ

The SETLL operation positions a file at the next record that has a key or relativerecord number that is greater than or equal to the search argument (key or relativerecord number) specified in factor 1. The file must be a full procedural file (identified by an F in position 16 of the file description specifications).

Figurative constants can be used to position the file. In most cases, *LOVAL positions the file so that the first read retrieves the record with the lowest key. In most cases, *HIVAL positions the file so that a READP retrieves the last record in the file, or a READ receives an end-of-file indication.

Remember the following when using the SETLL operation:If the SETLL operation is not successful (no records found condition), the file is positioned to the end of the file.When end of file is reached on a file being processed by SETLL, another SETLL can be issued to reposition the file.SETLL does not cause the system to access a data record. If you are only interested in verifying that a key actually exists, SETLL with an equal indicator(positions 58-59) is a better performing solution than the CHAIN operation in most cases. Under special cases of a multiple format logical file with sparse keys, CHAIN can be a faster solution than SETLL.

Example:In this example, the file ORDFIL contains order records. The key field is the ordernumber (ORDER) field. There are multiple records for each order. ORDFIL looks likethis in the calculation specifications:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

ORDER SETLL ORDFIL 55N55 GOTO NOTFND

79 of 150

Page 80: RPG400 Course Material

The SETLL operation positions the file at the first 1ð1 record. Because there are 101 records, indicator 55 is set on and the GOTO operation isnot processed.

SETGT (Set Greater Than)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQSearch argument/*HIVAL/*LOVAL

SETGT File Name NR ER __

The SETGT operation positions a file at the next record with a key or relative recordnumber that is greater than the key or relative record number specified in factor 1.The file must be a full procedural file (identified by an F in position 16 of the filedescription specifications).In this example, the file ORDFIL contains order records. The key field is the ordernumber (ORDER) field. There are multiple records for each order. ORDFIL looks likethis in the calculation specifications:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

ORDER SETGT ORDFIL READ ORDFIL 80

READ (Read a Record)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ READ File

Name/Record Name

Data structure __EREOF

The READ operation reads the record, currently pointed to, from a full procedural file

Example:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*LOVAL SETLL ORDFIL READ ORDFIL 80

*IN80 DOWEQ ‘0’...READ ORDFIL 80ENDDO

READE (Read Equal Key)Factor 1 Code Factor 2 Result Field Indicators

80 of 150

Page 81: RPG400 Course Material

HI LO EQ Search argument READE File

Name/Record Name

Data structure __EREOF

The READE operation retrieves the next sequential record from a full procedural fileif the key of the record matches the search argument.

Example:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*LOVAL SETLL ORDFIL ORDER READE ORDFIL 80

*IN80 DOWEQ ‘0’...

ORDER READE ORDFIL 80ENDDO

READP(Read a Previous Record)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

READP File Name/Record Name

Data structure __ERBOF

The READP operation reads the prior record from a full procedural file

Example:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*HIVAL SETGT ORDFIL READP ORDFIL 80

*IN80 DOWEQ ‘0’...READP ORDFIL 80ENDDO

REDPE (Read Prior Equal)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ Search argument REDPE File

Name/Record Name

Data structure __ERBOF

The REDPE operation retrieves the next prior sequential record from a full procedural

81 of 150

Page 82: RPG400 Course Material

file if the key of the record matches the search argument. If the key of the recorddoes not match the search argument,Example:

N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*HIVAL SETGT ORDFIL ORDER REDPE ORDFIL 80

*IN80 DOWEQ ‘0’...

ORDER REDPE ORDFIL 80ENDDO

CHAIN (Random Retrieval from a File)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ Search argument CHAIN File Name Data structure NRER __

The CHAIN operation retrieves a record from a full procedural file Example:N010N02No3 Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ ORDER CHAIN ORDFIL 90

*IN80 IFEQ ‘1’

WRITE (Create New Records)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

WRITE File Name Data structure __ER __

The WRITE operation writes a new record to a file.

Example:N010N02No3 Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ WRITE ORDFIL 91

UPDAT (Modify Existing Record)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ UPDAT File Name Data structure __ER __

82 of 150

Page 83: RPG400 Course Material

The UPDAT operation modifies the last record retrieved for processing from an update disk file or subfile. No other operation should be performed on the file between the input operation that retrieved the record and the UPDAT operation.

Remember the following when using the UPDAT operation: When a record format name is specified in factor 2, the current values in the program for

the fields in the record definition are used to modify the record. If some but not all fields in a record are to be updated, use the output specifications and

not the UPDAT operation. Before UPDAT is issued to a file or record, a valid input operation with lock (READ,

READC, READE, READP, REDPE, CHAIN, or primary/secondary file) must be issued to the same file or record. If the read operation returns with an error condition or if it was read without locking, the record is not locked and UPDAT cannot be issued. The record must be read again with the default of blank in position 53 to specify a lock request.

Consecutive UPDAT operations to the same file or record are not valid. Intervening successful read operations must be issued.

Example:N010N02No3 Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ ORDER CHAIN ORDFIL 90

*IN80 IFEQ ‘0’...UPDAT ORDFIL 89

DELET (Delete Record)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

Search Arguement DELET File Name __ER __

The DELET operation deletes a record from a database file. The file must be an update file (identified by a U in position 15. of the file description specifications) The deleted record can never be retrieved.If factor 1 contains no entry, the DELET operation deletes the current record (the last record retrieved). The record must have been locked by a previous input operation (for example, CHAIN or READ).

Example:N010N02No3 Factor 1 Code Factor 2 Result Field Indicators

HI LO EQDELET ORDFIL 89

83 of 150

Page 84: RPG400 Course Material

Calling Operations

CALL (Call a Program)Factor 1 Code Factor 2 Result

Field Indicators HI LO EQ

CALL Program name

Plist name __ER LR

The CALL operation passes control to the program specified in factor 2.Factor 2 must contain a character entry specifying the name of the program to becalled.

PARM (Identify Parameters)Factor 1 Code Factor 2 Result

Field Indicators HI LO EQ

Target field PARM Source field

Parameter

The result field must contain the name of a field, data structure, or array that is to be the parameter. Also, the result field of a non- *ENTRY PLIST can contain an array element. The result field can be numeric or character. The result field cannot contain *IN, *INxx, *IN,xx, a label, a literal, a data-area name, a data-area data structure name, a globally initialized data structure, a data structure with initialized subfields, a data structure with a compile time array as a subfield, or a table name. In addition, an array element, a data-structure subfield name, the name of a compile-time array and the name of a program status or file information data structure *INFDS) are not allowed in the result field of PARM specified for an *ENTRY PLIST. A field name can be specified only once in an *ENTRY PLIST.

If an array is specified in the result field, the area defined for the array is passed tothe called program. When a data structure with multiple occurrences is passed tothe called program, all occurrences of the data structure are passed as a singlefield. However, if a subfield of a multiple occurrence data structure is specified inthe result field, only the current occurrence of the subfield is passed to the calledprogram.

Each parameter field has only one storage location; it is in the calling program.The address of the storage location of the result field is passed to the called program on a PARM operation. If the called program changes the value of a parameter, it changes the data at that storage location. When control returns to the calling program, the value of the parameter in the calling program (that is, the result field) has changed. Even if the called program ends in error after it changes the value of a parameter, the changed value exists in the calling program. To preserve the information passed to the called program for later use, specify in factor 2 the name of the field that contains the information you want to pass to the called program. Factor 2 is copied into the result field, and the storage address of the result field is passed to the called program.

Because the program accesses the parameter fields by address, not field name,

84 of 150

Page 85: RPG400 Course Material

the calling and called parameters do not have to use the same field names forfields that are passed. The attributes of the corresponding parameter fields in thecalling and called programs should be the same. If they are not, undesirableresults may occur.When a CALL operation runs, the following occurs:

1. In the calling program, the contents of the factor 2 field of a PARM operation are copied into the result field (receiver field) of the same PARM operation.

2. In the called program, after it receives control and after any normal program initialization, the contents of the result field of a PARM operation are copied into the factor 1 field (receiver field) of the same PARM operation.

3. In the called program, when control is returned to the calling program, the contents of the factor 2 field of a PARM operation are copied into the result field (receiver field) of the same PARM operation. This move does not occur if the called program ends abnormally.

4. Upon return to the calling program, the contents of the result field of a PARM operation in the calling program are copied into the factor 1 field (receiver field) of the same PARM operation. This move does not occur if the called program ends abnormally or if an error occurs on the CALL operation.

PLIST (Identify a Parameter List)

Factor 1 Code Factor 2 Result Field

Indicators HI LO EQ

PLIST name PLIST

Factor 1 must contain the name of the parameter list. If the parameter list is theentry parameter list of a called program, factor 1 must contain *ENTRY. Only one*ENTRY parameter list can occur in a program. A parameter list is ended when anoperation other than PARM is encountered.

\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\C\ In the calling program, the CALL operation calls PROG2 andC\ allows PROG2 to access the data in the parameter list fields.C CALL 'PROG2' PLIST1C\C\ In the second PARM statement, when CALL is processed, theC\ contents of factor 2, *IN27, are placed in the result field,C\ BYTE. When PROG2 returns control, the contents of the resultC\ field, BYTE, are placed in the factor 1 field, *IN30. NoteC\ that factor 1 and factor 2 entries on a PARM are optional.C\C PLIST1 PLISTC PARM AMT 52C *IN30 PARM *IN27 BYTE 1\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C CALL 'PROG2'C\ In this example, the PARM operations immediately follow aC\ CALL operation instead of a PLIST operation.C PARM AMT 52

85 of 150

Page 86: RPG400 Course Material

C *IN30 PARM *IN27 BYTE 1

\...1....+....2....+....3....+....4....+....5....+....6....+....7...CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++C\ In the called program, PROG2, *ENTRY in factor 1 of theC\ PLIST statement identifies it as the entry parameter list.C\ When control transfers to PROG2, the contents of the resultC\ fields (FLDC and FLDG) of the parameter list are placed inC\ the factor 1 fields (FLDA and FLDD). When the called programC\ returns, the contents of the factor 2 fields of the parameterC\ list (FLDB and FLDE) are placed in the result fields (FLDCC\ and FLDG). All of the fields are defined elsewhere in theC\ program.C *ENTRY PLISTC FLDA PARM FLDB FLDCC FLDD PARM FLDE FLDG

Branching Operations

CABxx, TAG and CASxx which are previously described under compare operations also form a part of branching operations.

GOTO(Go to)

This statement transfers control within the program to the named statement

ITER (Iterate)

Forcibly branch to the end of a DO, DOUxx, or DOWxx condition bypassing all other statements in the DO group. Control is thus passed to the next iteration of the DO processing loop.

LEAVE (Leave)

Force Terminate a loop processing. Control would then pass to the statement immediately following the END of ENDyy statement as the case may be.

Array Operations

MOVEA (Move array)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

MOVEA Source Target + - ZB

The MOVEA operation transfers character or numeric values from factor 2 to the result field. (Certain restrictions apply when moving numeric values.) Factor 2 or the result field must contain an array. Factor 2 and the result field cannot specify the same array even if the array is indexed.

You can use MOVEA with a packed, binary, zoned, or character array. You can:

86 of 150

Page 87: RPG400 Course Material

° Move several contiguous character array elements to a single character field ° Move a single character field to several contiguous character array elements ° Move contiguous array elements to contiguous elements of another array.

Movement of data starts with the first element of an array if the array is not indexed or with the element specified if the array is indexed. The movement of data ends when the last array element is moved or filled.When the result field contains the indicator array, all indicators affected by the MOVEA operation are noted in the cross-reference listing.

Example:MOVEA FIELDA ARRAMOVEA ‘ABCDE’ ARRAMOVEA 25 ARRA

MOVEA FIELDA ARRA,XMOVEA ‘ABCDE’ ARRA,XMOVEA 25 ARRA,X

MOVEA FIELDA ARRA,3MOVEA ‘ABCDE’ ARRA,3MOVEA 25 ARRA,3

MOVEA ARRA FIELDAMOVEA ARRA,X FIELDBMOVEA ARRA,3 FIELDC

MOVEA ‘1111’ *IN,25MOVEA ‘0000’ *IN,25MOVEA ‘1010’ *IN,25

MOVEA *ALL’0’ *IN,25

XFOOT (Array Total)

Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

XFOOT Array name Sum + - Z

Sum of the individual elements of a numberic array in a named variable.

87 of 150

Page 88: RPG400 Course Material

XFOOT ARRAY FIELDA

LOKUP (Lookup)

Search for a character, named variable or a literal from a specified position in an array

FIELDA LOKUP ARRA‘ABCDE’ LOKUP ARRA25 LOKUP ARRA

FIELDA LOKUP ARRA,3‘ABCDE’ LOKUP ARRA,325 LOKUP ARRA,3

FIELDA LOKUP ARRA,X‘ABCDE’ LOKUP ARRA,X25 LOKUP ARRA,X

Please refer to ‘Arrays ,Tables and Data Structures’ section for More information

SORTA (Sort array)Factor 1 Code Factor 2 Result Field Indicators

HI LO EQ SORTA Array name

Sort an array of table specified in factor 2 in the sequence mentioned in the array or table specificationExample:

SORTA ARRA

Data Area Operations

Please refer to ‘Arrays ,Tables and Data Structures’ section for More information .Data area opcodes are discussed in detail.

Commitment Control Operations

COMIT (Commit)

Make all database changes since the previous commit or rollback operation.

COMIT

88 of 150

Page 89: RPG400 Course Material

ROLBK (Roll Back)

Undelete all database changes since the previous commit or rollback operation

RPG/400 IndicatorIndicators are logical switches of binary nature. Indicators may have a value of ‘0’ or ‘1’ at any time.

The Different kinds of indicators used in RPG/400 are:Overflow indicators – these are used to control of printing headings when skipping to new pages in a report. Indicators that may be used for overflow are

OA to OG, OV01 to 99

eecord identifiers – these indicators are used to identify the occurrence of a specific type of records in program-described files. Indicators that may be used are

01 to 99H1 to H9L1 to L9LRU1 to U8RT

Control indicators – these indicators are used to condition processing of printing of level breaks in RPG logic cycle programs.

Resulting Indicators – these indicators are specified for certain opcodes to identify the normal or abnormal processing of an op code. These Indicators are also used when checking for end-of-file conditions etc.

Examples For File processing:

RPG syntax to process an externally defined Physical File:

\...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U1.FSAMPLE IF E K DISKF\Entries for Physical file definition:

File name (col 7 -14) – Name of the Physical file

File Type (column 15)- letter I defines the physical file as an input file .Other types are U,O,C and D

File Designation (column 16)- Letter F defines the file is fully procedural file

89 of 150

Page 90: RPG400 Course Material

File Format(column 19)- Letter E denotes the File is externally defined. F denotes program defined

Record address type (Column 31)- K indicates the file is accessed in the key value order, a Blank entry denotes the file will be processed in arrival sequence.

Device (Columns 40 – 46)-Disk for Physical or logical file

RPG syntax to process a Program defined Physical File:

F Specification:\...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U1.FSAMPLE2 IF F 58 K DISKF\Entries for Physical file definition:

File name (col 7 -14) – Name of the Physical file

File Type (column 15)- letter I defines the physical file as an input file .Other types are U,O,C and D

File Designation (column 16)- Letter F defines the file is fully procedural file

File Format(column 19)- Letter F denotes program defined Record length(Column 24 -27) – Record length is 58

Record address type (Column 31)- Blank entry denotes the file will be processed in arrival sequence.

Device (Columns 40 – 46)- Disk for Physical or logical file

Input Specifications:

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..*IFilenameSqNORiPos1NCCPos2NCCPos3NCC................................*ISAMPLE2 AA 01 I....................................PFromTo++DField+L1M1FrPlMnZr...*I 3 10 PARTNOI 11 160QTYI 17 20 TYPEI 21 21 CODEI 22 25 LOCATN

Record Identification Section (Columns 7-42)

File/record Name (Column 7 -14) –Name of the inputfile defined

Sequence (columns (15-16)- Any two letters should be entered.

Record identifying indicator (column 19 -20) - A unique 2 digit Number

Addition Recommended Reading Material:1. SC09-1161-2 RPG/400 User’s Guide2 SC09-189-2 RPG/400 Reference Manual3 SC09-1349-01 SAA AD/Cycle RPG/400 Reference Manual

90 of 150

Page 91: RPG400 Course Material

91 of 150

Page 92: RPG400 Course Material

Chapter VII: Subfiles

A subfile is a special type of AS/400 display-file record. It is designed to hold column based list of data and to display that list in a column format. Sub Subfiles are used when you want to display multiple records on the display that have the same record layout.

The two major reasons for using subfiles are productivity and simplicity. A complex looking Display file can be totally written in a matter of minutes and takes only few lines of code. Modifying a subfile program is much easier than modifying a non-subfile program, especially since there is much less program code to handle. The reason subfile programs are easy to write and maintain is because most of the functionality resides within the DDS specifications of the display file.

A subfile may contain a maximum of 9999 Records. A subfile is of temporary nature and is active only for the duration of one program

execution.

Components of SubfileSubfile mainly requires two formats, v.i.z.,

SUBFILE FORMAT {SFL}. SUBFILE CONTROL FORMAT {SFLCTL}.

Subfile format {SFL} defines the layout of the records in the subfile. The Subfile format is actually a file that resides in memory. The subfile format describes the subfile records, and also contains data. The DDS keyword to describe the subfile format is SFL. The SFL Keyword is the mandatory keyword for any subfile.

Subfile control format {SFLCTL} defines the subfile as a whole, such as how many records it can contain, how many records to display on a screen and so on. It is also used to display the subfile, or to clear records out of a subfile. The DDS keyword used to define a subfile control format is SFLCTL.

There are 22 keywords in Subfiles 17 in SFLCTL format & 5 in SFL format.

The Mandatory Keywords in subfiles are SFL { Subfile Record Format} SFLCTL { Subfile Control Format} SFLDSP { Subfile Display} SFLDSPCTL { Subfile Display Control}

92 of 150

Page 93: RPG400 Course Material

SFLPAG { Subfile Page} SFLSIZ {Subfile Size }

Subfile Keywords

The following keywords are defined in the subfile control record format and are attributed to all the record for the subfile.

SFL Subfile Record FormatIdentifies the named record format as a subfile record format

SLFCLR Subfile clearUsed to indicate that when the associated indicator is set on the next output operation to the subfile record format to clear all the record of the subfile.

SFLCTL Subfile control record formatIdentifies the named record format as the subfile control record format

SFLDLT Delete subfileUsed to indicate that when the associated indicator is set on the next output operation to the subfile record format is to delete the subfile. The subfile would therefore be inactive.

SFLDROP Subfile dropUsed to indicate that when the associated command key is pressed, the secondary line(s) of a multiple line of subfile record are to be displayed. Upon the first output operation of the subfile, only the first line of each subfile record would be displayed.

SFLDSP Display subfileUsed to indicate that when the associated indicator is set on, the subfile is to be displayed upon the next output operation.

SFLDSPCTL Display subfile controlUsed to indicate that the associated indicator is set on, the subfile record format is to be displayed upon the next output operation.

SFLEND Subfile endUsed to indicate that when the associated indicator is sent on, the constant ‘More…’ normally displayed at the bottom of the every multi-page subfile is suppressed. This condition is exercised when there are no more subfile records to be displayed.

SFLINZ Initialize subfileUsed to indicate that when the associated indicator is set on, the next output operation to the subfile is to initialise all the alphanumeric variable in the subfile record to blanks and all the numeric variable to zeros in every record for the subfile.

SFLLIN Subfile lineUsed to specify the number of subfile records that should be displayed in the line of display

SFLMSG Subfile messageUsed to associate an error message with an error condition at the subfile control record level

SFLPAG Subfile pageUsed to specify the number of subfile records to be displayed in one page of display

SFLRCDNBR Subfile record number

93 of 150

Page 94: RPG400 Course Material

Used to associate a variable name which would contain the value of a valid subfile relative record number. The page of the subfile containing the record whose relative record number is present in this variable would be displayed upon the next output operation to the subfile.

SFLRNA Subfile not activeUsed to specify that the named subfile record format is to be made inactive. When used in association with the initialise subfile (SLFINZ) keyword, this has the effect of deleting the subfile.

SFLROLVAL Subfile roll valueUsed to specify the number of records that are to be paged up/down when the Roll Up/Roll Down keys are used

SFLSIZ Subfile sizeUsed to specify the maximum number of records that are to displayed in a subfile at a time. The following keyword is the only keyword that is applicable at the subfile record. Thus this keyword, may be applicable or not to individual records in the subfile.

SFL Subfile record formatIdentifies the named record format as a subfile record format

SFLNXTCHG Subfile next changed recordAssociate an indicator with this keyword. This indicator may be set on/off individually for each record in the subfile. If this indicator set on, then the modified data tag for the associated subfile record is set on. In this case, the subfile record can be picked by a READC operation within the program.

Subfile Data Description Specification :

***************************************************************************************************************** * Display File for LOAD-ALL-SUBFILES * ***************************************************************************************************************** A DSPSIZ(24 80 *DS3) A CA03(03 'EXIT') A R SFLREC SFL A CUSAD R O 8 51REFFLD(RCUST/CUSAD G2KFLIB5/CUST) A CUSNM R O 8 17REFFLD(RCUST/CUSNM G2KFLIB5/CUST) A CUSNO R O 8 3REFFLD(RCUST/CUSNO G2KFLIB5/CUST) A R SFLCTL SFLCTL(SFLREC) A OVERLAY A SFLDSP A SFLDSPCTL A 10 SFLCLR A 20 SFLEND(*MORE) A SFLSIZ(0015) A SFLPAG(0014) A 1 20' WORK SCREEN FOR CUSTOMER ENQUIRY' A 1 3USER A 1 66DATE A EDTCDE(Y) A 5 4'CUST NUMBER' A 5 19'CUSTOMER NAME ' A 5 54'CUSTOMER ADDRESS' A R FOOTER A OVERLAY A 24 3'F3 = EXIT' *********************************************** End of data ******************* **********************

94 of 150

Page 95: RPG400 Course Material

Handling Subfiles in RPG ProgramsFile Declarations The Display file is declared as file in the file specification. Details that are included are Name of the display file Type which is ‘C’ and Designation ‘F’ to indicate combined Fully procedural file Device definition which is ‘WORKSTN’ to indicate a display file In the Continuation specification of the file specification, a variable name is identified as

the subfile relative record number with the following RPG reserved wordRRNBR KSFILE SUBFILIn the above example, a subfile record format SUBFIL with a relative record number RRNBR is declared.

Example:

******************************************* Beginning of data ***************************************** * Example for File specification * * Physical File - CUST * * Display File - SFLCUS * ****************************************************************************************************************** FCUST IF E K DISK FSFLCUS CF E WORKSTN F COUNT KSFILE SFLREC ******************************************* End of data *************************************************

Calculation Specification

Within the ‘C’ specification itself, there would not be any reference in the display file name.

All references would be to particular record formats only. Individual record formats may be returned or read from the screen If an output operation is done, (that is WRITE or related operation) the display is

sent to the screen. If an input operation is done, (that is, READ or related operation) the display is

read from the screen and the displayed data is made available to the program. At this point the control passes to the program.

Steps Involved In Subfile Programming : INITIALIZE - Initialize the RRN to Zero. CLEAR - Set On the SFL clear indicator, clear SFLCTL, write the SFLCTL

& setoff the Indicator BUILD - Load the subfile by reading the PF & writing the Subfile record Format. DISPLAY - Set on the SFLDSPCTL indicator & EXFMT the SFLCTL PROCESS - Process Changed Records Using READC or CHAIN opcodes

Multi page subfiles:There are three options for managing a multipage subfile:

95 of 150

Page 96: RPG400 Course Material

1. Load all Subfile 2. Expanding Subfile (Adding a page at a time.3. Single page Subfile

Subfile Load Options- Pros and Cons.

Subfile Load Option

Code Issues User Issues

1. Load all subfile Simplest code Limit of 9999 records

User has to wait until entire file is loaded.

Data is only updated when a user makes a change that requires reloading the subfile

Changes made to the data by other users or other programs after the subfile is loaded will not be apparent.

2.Expanding subfile Code is more complex. Limit of 9999 records.

Brief delay whenever a page is loaded. Pages added when the Page Down key is

pressed are updated at the time they are added to the subfile. However , subsequent changes to the data made by other users or Programs are not displayed until a user makes a change that requires reloading the subfile.

3. Single Page Subfile Most complicated Code .

Use least memory. No Size limit.

Brief delay whenever the page up key or Page down key is pressed.

Data is always updated at the time of processing a page up/Page down request.

Load all Subfile:

The first method of loading a subfile is to load all of the records that you want to display into the subfile at one time. After this load is complete you can display the subfile, which gives the users access to all of the subfile records by allowing them to roll backwards and forwards. Every record that you want to display must be loaded into the subfile before displaying the subfile. Sometimes you may only load a few records into the subfile, other times you might load hundreds. But for the load-all subfile method, you simply load every record in before you display the subfile.Loading the subfile is accomplished by writing the subfile records to the subfile format. Once every record has been loaded, you can display the subfile by writing the subfile control format. The subfile itself handles the roll keys, and you don’t even have to make reference of them in either the RPG program or the DDS specifications for the display file.

96 of 150

Page 97: RPG400 Course Material

SUBFILE PAGE < SUBFILE SIZEOR

SUBFILE SIZE = SUBFILE PAGE + 1.

Physical file Test:

A UNIQUE A R TSTREC A CODE 3 A NAME 20 A AGE 2P 0 A PHONE 10P 0 A K CODE A*************** A Subfile for Load All: A*************** A R DSFRCD SFL A*%%TS SD 20040203 031411 RTAMIL REL-V5R1M0 5722-WDS A CODE R O 5 4REFFLD(TSTREC/CODE RTAMIL/TEST) A NAME R O 5 12REFFLD(TSTREC/NAME RTAMIL/TEST) A AGE R O 5 33REFFLD(TSTREC/AGE RTAMIL/TEST) A PHONE R O 5 48REFFLD(TSTREC/PHONE RTAMIL/TEST) A R DSFCTL SFLCTL(DSFRCD) A*%%TS SD 20040203 034504 RTAMIL REL-V5R1M0 5722-WDS A SFLSIZ(0015) A SFLPAG(0014) A CF03(03) A CF05(05) A OVERLAY A 90 SFLDSP A 91 SFLDSPCTL A 93 SFLCLR A 94 SFLEND(*MORE) A 1 29'Load All Subfile Example' A DSPATR(UL) A 2 30'For Demo Purpose Only' A DSPATR(BL) A DSPATR(UL) A 4 4'Code' A DSPATR(UL) A 4 12'Name' A DSPATR(UL) A 4 33'Age' A DSPATR(UL) A 4 48'Phone' A DSPATR(UL)

The following is the display file for load all subfiles.

******************************* Beginning of data ******************************************* * Example for EXPANDING SUBFILE * * Physical File - TEST * * Display File - TESTDSP ************************************************************************************************* RPG program for load all subfiles FTEST IF E K DISK FTESTDSP CF E WORKSTN F SFLRRNKSFILE DSFRCD C* C EXSR INZSR

97 of 150

Page 98: RPG400 Course Material

C EXSR BLDSR C EXSR DSPSR C SETON LR C* C INZSR BEGSR //Clear subfile C Z-ADD*ZEROS SFLRRN 40 C SETON 93 CLRSFL C WRITEDSFCTL C SETOF 93 C ENDSR C* C DSPSR BEGSR C SETON 9091 //Display subfile C *IN03 DOUEQ'1' C WRITESFLFTR C EXFMTDSFCTL C *IN03 IFEQ '0' C *IN05 IFEQ '1' C EXSR BLDSR C ENDIF C ENDIF C* C ENDDO C ENDSR C* C BLDSR BEGSR //Build Subfile C *LOVAL SETLLTSTREC C READ TSTREC 94 C *IN94 DOWEQ'0' C ADD 1 SFLRRN C WRITEDSFRCD C READ TSTREC 94 C ENDDO C ENDSR *************************** End *******************

98 of 150

Page 99: RPG400 Course Material

Expanding Subfile:

The second method of loading a subfile is to start by loading a specific number of records into the subfile. You can then display the subfile to the user. If the information the user needs is not currently loaded into the subfile, your program can load more subfile records behind those already loaded. This technique is known as an expanding subfile.If the user rolls forward (ROLL UP), then the subfile automatically switches the display to subfile page two for you. Here you have to set the indicator for ROLL UP keyword in DDS and handle it in the RPG program. ROLL DOWN(Page Up) is automatically taken care by the system.

One advantage of expanding subfile over a load-all-subfile is that the subfile is displayed to the user in a very stable amount of time, depending on how many records the program loads. With the expanding subfile, you can divide the load process into a fixed number of records. For instance, suppose you load six records at a time in an expanding subfile, It would not matter if there were a possibility of loading 5,000 records into the subfile, your program would only load six records before it displays the subfile to the user. This method displays the screen to the user very quickly.

SUBFILE PAGE << SUBFILE SIZE.

The following is the DDS code for display file (Expanding Subfile)

A* ******************************************************************* A* * EXPANDING SUBFILES DATE - 13/05/1999. * A* ************************************************************************************ A******************************* A Subfile for Expanding Subfile: A****************************** A R DSFRCD1 SFL A CODE R O 5 4REFFLD(TSTREC/CODE RTAMIL/TEST) A NAME R O 5 12REFFLD(TSTREC/NAME RTAMIL/TEST) A AGE R O 5 33REFFLD(TSTREC/AGE RTAMIL/TEST) A PHONE R O 5 48REFFLD(TSTREC/PHONE RTAMIL/TEST) A R DSFCTL1 SFLCTL(DSFRCD1) A*%%TS SD 20040203 034844 RTAMIL REL-V5R1M0 5722-WDS A SFLSIZ(0015) A SFLPAG(0006) A CF03(03) A CF05(05) A ROLLUP(08) A OVERLAY A 90 SFLDSP A 91 SFLDSPCTL A 93 SFLCLR A 94 SFLEND(*MORE) A 1 29'Expanding Subfile Example' A DSPATR(UL) A 2 30'For Demo Purpose Only' A DSPATR(BL) A DSPATR(UL) A 4 4'Code' A DSPATR(UL) A 4 12'Name' A DSPATR(UL)

99 of 150

Page 100: RPG400 Course Material

A 4 33'Age' A DSPATR(UL) A 4 48'Phone' A DSPATR(UL) A*********** A SFLRCDNBR A*********** A RCDNBR 4S 0H SFLRCDNBR A******************************* *******************************************************

The following is the RPG program for Expanding subfile**************** Beginning of data************************************************************ * Example for PAGE-BY-PAGE BUILD SUBFILE * Physical File - TEST * Display File - TESTDSP *******************************************************************************

******************************* Beginning of data ********************************* FTEST IF E K DISK FTESTDSP CF E WORKSTN F SFLRRNKSFILE DSFRCD1 C* C EXSR INZSR C EXSR BLDSR C EXSR DSPSR C SETON LR C* C *INZSR BEGSR C* C Z-ADD*ZEROS SFLRRN 40 C *LOVAL SETLLTSTREC C ENDSR C* C INZSR BEGSR C SETON 93 CLRSFL C WRITEDSFCTL1 C SETOF 93 C ENDSR C* C DSPSR BEGSR C SETON 9091 C *IN03 DOUEQ'1' C WRITESFLFTR C EXFMTDSFCTL1 C *IN03 IFEQ '0' C *IN05 IFEQ '1' C *LOVAL SETLLTSTREC C EXSR BLDSR C ENDIF C *IN08 IFEQ '1' //Page Down or Rollup C EXSR BLDSR C ENDIF C ENDIF C* C ENDDO C ENDSR C* C BLDSR BEGSR C Z-ADD*ZEROS COUNT 40 C READ TSTREC 94 C *IN94 DOWEQ'0' C* COUNT ANDLT6 //SFLPAG = 3 C ADD 1 SFLRRN C ADD 1 COUNT C WRITEDSFRCD1 C COUNT IFEQ 1 C Z-ADDSFLRRN RCDNBR // Move RRN to SFLRCDNBR C ENDIF

100 of 150

Page 101: RPG400 Course Material

C COUNT IFEQ 6 C LEAVE C ENDIF C READ TSTREC 94 C ENDDO C ENDSR ************************************End of data **********************

Single Page Subfile:

The third method of loading is known as a single-page load. In this process you only load the number of subfile records that can be displayed on the screen at one time. If the information the user needs is not in the subfile, then the existing subfile records are discarded, and another page worth of subfile records is loaded.If the information the user wants to see is not on this page of subfile records, then you can’t just add more records to the subfile like you do in an expanding subfile method. You must first clear the existing records out of the subfile. You clear a subfile by setting on an indicator located in the subfile control format that controls the clear operation. Then you write the subfile control format, which removes all data from the subfile.

This type of subfile is used when there are more than 9999 records in a database.

SUBFILE PAGE = SUBFILE SIZE

The following is the DDS for Page-By-Page Build subfile

A***************************************************************************************************************** A* Display File for LOAD-ALL-SUBFILES * A***************************************************************************************************************** A******************************* A Subfile Single Page Subfile: A******************************* A R DSFRCD2 SFL A CODE R O 5 4REFFLD(TSTREC/CODE RTAMIL/TEST) A NAME R O 5 12REFFLD(TSTREC/NAME RTAMIL/TEST) A AGE R O 5 33REFFLD(TSTREC/AGE RTAMIL/TEST) A PHONE R O 5 48REFFLD(TSTREC/PHONE RTAMIL/TEST) A R DSFCTL2 SFLCTL(DSFRCD2) A SFLSIZ(0006) A SFLPAG(0006) A CF03(03) A CF05(05) A N94 ROLLUP(08) A ROLLDOWN(07) A OVERLAY A 90 SFLDSP A 91 SFLDSPCTL A 93 SFLCLR A 94 SFLEND(*MORE) A 1 29'Expanding Subfile Example' A DSPATR(UL) A 2 30'For Demo Purpose Only' A DSPATR(BL) A DSPATR(UL) A 4 4'Code'

101 of 150

Page 102: RPG400 Course Material

A DSPATR(UL) A 4 12'Name' A DSPATR(UL) A 4 33'Age' A DSPATR(UL) A 4 48'Phone' A DSPATR(UL)************************************ End of data *******************************************************

RPG program for Page-By-Page Build Subfile

**************** Beginning of data************************************************************ * Example for PAGE-BY-PAGE BUILD SUBFILE * Physical File - TEST * Display File - TESTDSP ******************************************************************************* FTEST IF E K DISK FTESTDSP CF E WORKSTN F SFLRRNKSFILE DSFRCD2 C* C* EXSR INZSR C EXSR BLDSR C EXSR DSPSR C SETON LR C* C *INZSR BEGSR C* C Z-ADD*ZEROS SFLRRN 40 C *LOVAL SETLLTSTREC C ENDSR C* C INZSR BEGSR C Z-ADD*ZEROS SFLRRN 40 C SETON 93 CLRSFL C WRITEDSFCTL2 C SETOF 93 C ENDSR C* C DSPSR BEGSR C SETON 9091 C *IN03 DOUEQ'1' C WRITESFLFTR C EXFMTDSFCTL2 C* C *IN03 IFEQ '0' C *IN05 IFEQ '1' C *LOVAL SETLLTSTREC C EXSR BLDSR C ENDIF C* C *IN08 IFEQ '1' C EXSR BLDSR C ENDIF C* C *IN07 IFEQ '1' C EXSR BLDBSR C ENDIF C ENDIF C* C ENDDO C ENDSR C* C BLDSR BEGSR C Z-ADD*ZEROS COUNT 40 C EXSR INZSR C READ TSTREC 94 C *IN94 DOWEQ'0'

102 of 150

Page 103: RPG400 Course Material

C COUNT ANDLT6 C ADD 1 SFLRRN C ADD 1 COUNT C COUNT IFEQ 1 C MOVE CODE FCODE 3 C ENDIF C WRITEDSFRCD2 C COUNT IFEQ 6 C LEAVE C ENDIF C READ TSTREC 94 C ENDDO C ENDSR C***reposition C BLDBSR BEGSR C *IN94 IFEQ '1' C *HIVAL SETGTTSTREC C ELSE C FCODE SETLLTSTREC C ENDIF C*** C DO 7 C READPTSTREC 95 C *IN95 IFEQ '1' C *LOVAL SETLLTSTREC C LEAVE C ENDIF C ENDDO C*** C Z-ADD*ZEROS COUNT 40 C EXSR BLDSR C ENDSR

************************************ End of data *******************************************************

Fold and Drop capabilities :The data to be displayed on a screen frequently exceeds the space available to display it. This is especially true when you design displays with subfiles that are usually limited to a single row of 80 characters. The subfile keyword that initially displays only the first line of the subfile records and reacts to a function key by switching into a multi line format is SFLDROP .Conversely , The keyword SFLFOLD initially displays the subfile in a multi line format and reacts to a function key by switching to a single line format . Ex :***************************************************************************************************************** * Example for Fold and * ***************************************************************************************************************** A DSPSIZ(24 80 *DS3) A CA03(03 'EXIT') A R SFLREC SFL A CUSAD R O 8 51REFFLD(RCUST/CUSAD G2KFLIB5/CUST) A CUSNM R O 8 17REFFLD(RCUST/CUSNM G2KFLIB5/CUST) A CUSNO R O 8 3REFFLD(RCUST/CUSNO G2KFLIB5/CUST) A R SFLCTL SFLCTL(SFLREC) A OVERLAY A SFLDSP A SFLDSPCTL A 10 SFLCLR A 20 SFLEND(*MORE) A SFLDROP(CF06) A SFLSIZ(0009)

103 of 150

Page 104: RPG400 Course Material

A SFLPAG(0004)

…….. ……* CF06 is the function key that causes the display file to switch from the drop(single line format ) to the fold(multiline format)

* Subfile page size( SFLPAG) has been changed to the number of folded records that can be displayed.

Other interesting Subfile Keywords:

SFLRCDNBR , SFLMODE, SFLCSRRRN, SFLROLVAL

Additional Recommended Reading Material

1. SC21-9658-2 Data Management Guide

104 of 150

Page 105: RPG400 Course Material

Chapter VIII: Arrays, Tables and Data structures

Arrays: An array may be defined as an arrangement of computer memory positions in one (or multiple) dimension with each position having the same attributes.

RPG only supports one dimensional arrays and does not directly support multi dimensional arrays. How ever they may be simulated by defining one or more Multiple Occurrence Data structure

Array Description :

The Number of elements, size of the elements ,type and sequence are specified in the extension specifications:

All Extension Specification instructions must include an E in the column n 6 and immediately follow the last File Description statement.

1. Columns 7-10 not used.2. From Filename (columns 11-18).Required for Prerun Time arrays. File name, specified

in a File Description statement (T in columns 16) as program-defined (F in column 19) must be entered left-justified in this field.

3. To Filename (columns 19-26).Optional for Prerun Time arrays. If the array data is to the end of the program, the name of the output file must be entered left-justified in this field.

4. Array Name(columns 27-32).Programmer –supplied array name must be entered in this field .If the array is to be indexed , the required comma and index name or literal must be considered in the array specified in the program.

5. Number of Entries Per record (columns 33-35).Specifies how many individual array elements are stored on a record .Entry is only for Compile and Prerun Time arrays.

6. Number of Entries Per Array (columns 36-39) specifies how many array elements are stored in the array. Required for all array types.

7. Length of Entry (columns 40-42).Specifies the size of the array elements. All elements of an array must be the same size. Elements in character arrays may be defined from 1 to 256 bytes. Numeric array elements may be defined from 1 to 30 bytes

8. P/B/L/R(column 43)If the numeric data in a Prerun or Run Time array is stored in packed decimal format , the letter P must be specified in this field. If the data is stored in binary format, a B must be specified .If no entry is specified, the numeric array data is stored as zoned decimal .Compile Time array data is entered in a zoned decimal

105 of 150

Page 106: RPG400 Course Material

format .An L entered in this field indicates that a separate sign stored to the left of the value and an R to the right.

9. Decimal Positions (column 44) A blank in this field indicates that the array is character .A number from 0 to 9 defines the array elements as numeric with the indicated implied decimal positions. The entry cannot be larger than the Length of Entry size.

10. Sequence (A/D) (column 45) If the array is not in a sorted order, this filed must be blank .If the data is in an ascending order, an A may be entered .On the other hand, if the array data is in a descending order, a D may be specified .If sequence is specified, an “early exit” is provided for an unsuccessful equal lookup condition, reducing run times.

11. Array Name(Alternating Format)(columns 46-51).An array name entered in this filed indicates that two or more entries from two related array are stored in each stored in each record, for example ,data for an SSNO element followed by data for a NAME element. Number of entries Per Record specifies how many” pairs” are included on a record. Only valid for Compile and Prerun Time arrays.

12. Columns 52-57.These four fields relate to the attribute of the alternating array. Refer to items 7, 8, 9 and 10 for an explanation of these fields.

Loading of an array: Arrays can be classified into three types by the nature of loading.

1) Compile Time array2) Prerun time array3) Run time array

Compile time array:

Compile time arrays data is an integral “Hard coded “ part of an RPG Program. It must be included after a ** control statement entered in column 1 and 2 and follow the last (O) output statement in the program.Salient features:

Array Data is permanent. Array data is separated from the last output statement in the program by ** in columns

1 and 2. Data is loaded when the program is created.

Example:

106 of 150

Page 107: RPG400 Course Material

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* E MTH 6 12 9 E DAYS 12 12 2 0

(other RPG program statements )

0<----------------------------(last output specification statement) **---------------------------------(delimits compile time array from program)JANUARY FEBRUARY MARCH APRIL MAY JUNE Data values for an array must JULY AUGUST SEPTEMBER OCTOBER NOVENBER DECEMBER be the seme size .Compile time** <--------------------------------------------------------------------------------------------------------- Arrays are separated by * * 312831303130313130313031Related array data must be entered in the order the arrays are specified in the Extension form.

Note: Array data items must be size of the elements defined in the Extension form. Smaller numeric data is padded with high-order zeros and alphanumeric data is padded with low-order blanks.

Extension Specification syntax and related data for two Compile Time arrays.

Prerun time Array:

Data for Prerun Time arrays is stored externally from the program in a physical file. When processed , the array is created and loaded with the data from the physical file before any other files are processed.

Salient features: Array Data is stored in physical file File that stores the array data is program defined in the file description space, as input

with a T in column 16 and an E in column 39. Array defined in the Extension specifications. ‘T’ File is read before any input , calculations or Output is executed.

Example:

F Specification :* Must be defined as an input table file * Must be program-defined .Indicates array attributes are defined in the Extension Specification

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* FARYFILE IT F 11 EDISK

E Specification :

* File name defined in the File Description Specifications with a T in the column 16 must be entered here*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* E ARYFILE MTH 1 12 9 DAYS 2 0

107 of 150

Page 108: RPG400 Course Material

Run time array:

Data for run time array may be stored in an externally defined physical file, the data may be loaded in the input specifications or loaded by one or more calculation statements for the arrays that are defined in the Extension specifications without a Number of Entries Per Record Field entry.

Salient Features:Data Loaded via Input specifications:

A physical file externally or program defined stores the array data. Array defined in the Extension Specifications and elements are referenced

in the input specifications. Program is executed and physical data is read. As a record is read , the

array is loaded with data . This procedure is followed for each record in the file.

Data loaded Via calculation Specification: Array is defined in the Extension Specifications. Program is executed and the array is loaded by instructions in calculation

specifications.

108 of 150

Page 109: RPG400 Course Material

Example:Data Loaded via Input specifications:

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* 2 1DATAFLE IP E DISK

Physical File is externally defined

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* 01 E ARY 4 8

Number of Entries per record field is not used for Run Timearrays(loaded in Input or Calculation Specifications)

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* 01 1DATAFLER 02 1 FLD1 ARY,1 03 1 FLD2 ARY,2 04 1 FLD3 ARY,3 05 1 FLD4 ARY,4

Field names in the physical file Array name, comma and element record format that store the data number are entered in the field name for the Run Time array are entered columns.beginning in column 21.

Note: The fields in the physical file’s record do not have to be contiguous and may be scattered within the record format.

Data loaded Via calculation Specification:

109 of 150

Page 110: RPG400 Course Material

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* E SALE 5 7 2 Loaded On Input E TOTL 5 8 2 Loaded On Calc

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* C ADD SALE TOTL

Searching ArraysThe LOKUP operation can be used to search arrays.

Searching an Array without an Index

When searching an array without an index, use the status (on or off) of the resulting indicators to determine whether a particular element is present in the array. Searching an array without an index can be used for validity checking of input data to determine if a field is in a list of array elements. Generally, an equal LOKUP is requested.

In factor 1 in the calculation specifications, specify the search argument (data forwhich you want to find a match in the array named). Factor 1, the search argument, can be:

A character or numeric literal A field name A data structure name An array element A table name.

The result field cannot be used.The search starts at the beginning of the array and ends at the end of the array or when the conditions of the lookup are satisfied. Whenever an array element is found that satisfies the type of search being made (equal, high, low), the resulting indicator is set on.

Example:

\...1....+....2....+....3....+....4....+....5....+....6....+....7... FFilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U1.FARRFILE IT F 5 EDISKF\E....FromfileTofile++Name++N/rN/tbLenPDSArrnamLenPDSCommentsE ARRFILE DPTNOS 1 50 5 0 DEPT NUMBERSE\CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments+++++++C\ The LOKUP operation is processed and, if an element of DPTNOS equalC\ to the search argument (DPTNUM) is found, indicator 2ð is set on.C DPTNUM LOKUPDPTNOS 2ðC\

110 of 150

Page 111: RPG400 Course Material

C\ Otherwise, indicator 2ð is not set on and the GOTO statementC\ conditioned by N2ð causes a branch to the BADNUM TAG.C N20 GOTO BADNUMC :C : CalculationsC :C BADNUM TAG

ARRFILE, which contains department numbers, is defined in the file description spec-ifications as an input file (I in position 15) with an array file designation (T in posi-tion 16). The file is program described (F in position 19), and each record is 5positions in length (5 in position 27). The E in position 39 indicates that the file isfurther described in the extension specifications.In the extension specifications, ARRFILE is defined as containing the array DPTNOS.The array contains 50 entries (positions 38 and 39). Each entry is 5 positions inlength (position 42) with zero decimal positions (position 44). One departmentnumber can be contained in each record (1 in position 35). However, each recorddoes not have to contain an entry. Any record that does not contain an entry isfilled with zeros.

Searching an Array with an Index

To find out which element satisfies a LOKUP search, start the search at a particular element in the array. To do this type of search, make the entries in the calculation specifications as you would for an array without an index. However, in positions 33 through 42, enter the name of the array to be searched, followed by a comma and a numeric constant or the name of a numeric field (with zero decimal positions) containing the number of the element to be used. The numeric constant or numeric field provides the number of the element at which the search is to start. Thisnumeric constant or field is called the index because it points to a certain element in the array. All other rules that apply to an array without an index apply to an array with an index.

Example:

\...1....+....2....+....3....+....4....+....5....+....6....+....7...FFilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U1.FARRFILE IT F 5 EDISKF\E....FromfileTofile++Name++N/rN/tbLenPDSArrnamLenPDSComments+++++++++E ARRFILE DPTNOS 1 5ð 5 ð DPTDSC 2ð DEPT NO/DESCRPTNE\CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments+++++++C\ The Z-ADD operation begins the LOKUP at the first element in DPTNOS.C Z-ADD1 X 3ð SET X FOR LOKUP

C\ At the end of a successful LOKUP, when an element has been foundC\ that contains an entry equal to the search argument DPTNUM,C\ indicator 2ð is set on and the MOVE operation places the departmentC\ description, corresponding to the department number, into DPTNAM.C DPTNUM LOKUPDPTNOS,X 2ðC\ If an element is not found that is equal to the search argument,C\ the GOTO operation conditioned by N2ð causes a branch to BADNUM.C N20 GOTO BADNUMC MOVE DPTDSC,X DPTNAM 2ðC BADNUM TAG

This example shows the same array of department numbers, DPTNOS, asFigure 109 on page 396. However, an alternating array of department descriptions, DPTDSC, is also defined in positions 46 through 51 of the extension specifications. Each element in DPTDSC is 20

111 of 150

Page 112: RPG400 Course Material

positions in length (positions 53 and54). Any record in DPTNOS that does not contain an entry is filled with zeros. Any record in DPTDSC that does not contain an entry is filled with blanks.

Specifying an Array in CalculationsAn entire array or individual elements in an array can be specified in calculationspecifications. You can process individual elements like fields. Remember, if anarray element is to be used as a result field, the array name with the comma andindex cannot exceed 6 characters.

To specify an entire array, use only the array name, which can be used as factor 1,factor 2, or the result field. The following operations can be used with an arrayname:

ADD Z-ADD SUB Z-SUB MULT DIV SQRT MOVE MOVEL MOVEA MLLZO MLHZO MHLZO MHHZO DEBUG XFOOT LOKUP SORTA PARM DEFN CLEAR RESET CHECK CHEKR SCAN.

Several other operations can be used with an array element only but not with thearray name alone. These operations include but are not limited to:

BITON BITOF COMP CABxx TESTZ

112 of 150

Page 113: RPG400 Course Material

TESTN TESTB MVR DOUxx DOWxx IFxx SUBST CAT.

When specified with an array name without an index, certain operations are repeated for each element in the array. These are

ADD Z-ADD SUB Z-SUB MULT DIV SQRT MOVE MOVEL MLLZO MLHZO MHLZO MHHZO

The following rules apply to these operations when an array name without an index is specified: When factors 1 and 2 and the result field are arrays with the same number of elements,

the operation uses the first element from every array, then the second element from every array until all elements in the arrays are processed. If the arrays do not have the same number of entries, the operation ends when the last element of the array with the fewest elements has been processed. When factor 1 is not specified for the ADD, SUB, MULT, and DIV operations, factor 1 is assumed to be the same as the result field.

When one of the factors is a field, a literal, or a figurative constant and the other factor and the result field are arrays, the operation is done once for every element in the shorter array. The same field, literal, or figurative constant is used in all of the operations.

The result field must always be an array. If an operation code uses factor 2 only (for example, Z-ADD, Z-SUB, SQRT, ADD, SUB, MULT, or DIV do not have factor 1 specified) and the result field is an array, the

operation is done once for every element in the array. The same field or constant is used in all of the operations.

Resulting indicators (positions 54 through 59) cannot be used because of the number of operations being processed.

Tables :There is no physical difference between a table and array. But functionally, an array can be addressed element by element while a table can only be addressed wholly. Also one element in a Table can be accessed at a time unlike an array.

113 of 150

Page 114: RPG400 Course Material

Data Structures: The RPG/400 program allows you to define an area in storage and the layout of the fields, called subfields, within the area. This area in storage is called a data structure. You can use a data structure to:

Divide a field into subfields Change the format of a field Group noncontiguous data in a contiguous format Define an area of storage in more than one format. Define multiple occurrences of a set of data

In addition, there are three special data structures, each with a specific purpose:

A data area data structure (identified by a U in position 18 of the data structure statement) A file information data structure (referred to by the keyword INFDS on a file

description specifications continuation line) A program-status data structure (identified by an S in position 18 of the data structure

statement). Data structures can be program-described or externally described.

A program-described data structure is identified by a blank in position 17 of the data structure statement. The subfield specifications for a program-described data structure must immediately follow the data structure statement.

An externally described data structure, identified by an E in position 17 of the data structure statement, has subfield descriptions contained in an externally described file with one record format. At compile time, the RPG/400 program uses the external name to locate and extract the external description of the data structure subfields. An external subfield name can be renamed in the program, and additional subfields can be added to an externally described data structure in the program.

Format of Data Structure Subfields in Storage:

Subfields in a data structure are stored in the format specified in position 43 of the data structure subfield specifications. The possible entries for a program-described data structure are:

Entry ExplanationBlank Subfield is in zoned-decimal format or is character data,depending on the entry in position 52

of the subfield specifications. P Subfield is in packed-decimal format.B Subfield is in binary format.

____________ ________________________________________________________

114 of 150

Page 115: RPG400 Course Material

Because the subfields of a data structure are maintained in the format specified, The compiler generates the necessary conversions to process the required function. These conversions can occur at the following times:

When a record is being read At detail or total calculation time At detail or total output time.

Data Structure Statement Specifications:

Data structure statements are defined on the input specifications and must follow all input specifications for records.

The specifications for data structure statements are:

Position Entry 6 I 7-12 Name of the data structure being defined. This entry is optional for a

program-described data structure, and is required for an externally described data structure, a file information data structure (INFDS), and a data area data structure.

13-16 Blank 17

Blank: Program-described data structure. E: Externally described data structure. The data structure subfield definitions are retrieved from an externally described record format.

18

Blank: Other than a program status, data area or initialized data structure. I: Globally initialized data structure. S: Program-status data structure. U: Data area data structure.

19-20 DS 21-30

Blank: The data structure is program described. Entry: This is the name of the file whose first record format contains the field descriptions used as the subfield descriptions for this data structure.

31-43 Blank 44-47

Blank: A single occurrence data structure. nnnn: A number (right-adjusted) indicating the number of occurrences of the data structure. Note: This entry must be blank for a data area data structure, a file information data structure, and a program-status data structure.

48-51

Length of data structure (optional). This entry must beright-adjusted.

52-74 Blank

115 of 150

Page 116: RPG400 Course Material

Examples:

Divide a field into subfields:

IDsname....NODsExt-file++.............OccrLen+......................*IPARTNO DSI..............Ext-field+............PFromTo++DField+...............*I 1 4 MFGI 5 10 DRUGI 11 13 STRNTHI 14 160COUNTI*

Using Data Structure to Group fields :

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..*IFilenameSqNORiPos1NCCPos2NCCPos3NCC................................*ITRANSACTNS 01 1 C1 2 C2I....................................PFromTo++DField+L1M1FrPlMnZr...*I 3 10 PARTNOI 11 160QTYI 17 20 TYPEI 21 21 CODEI 22 25 LOCATNIDsname....NODsExt-file++.............OccrLen+......................*IPRTKEY DSI..............Ext-field+............PFromTo++DField+...............*I 1 4 LOCATNI 5 12 PARTNOI 13 16 TYPE

When you use a data structure to group fields, fields from non-adjacent locations on the input record can be made to occupy adjacent internal locations. The area can then be referred to by the data structure name or individual subfield name.

Change the format of the Field:

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..*IFilenameSqNORiPos1NCCPos2NCCPos3NCC................................*IINPUT SM 01 I....................................PFromTo++DField+L1M1FrPlMnZr...*I 1 60DATE I 1 2 MM I 3 4 DD I 5 6 YYIDsname....NODsExt-file++.............OccrLen+......................*I DSI..............Ext-field+............PFromTo++DField+...............*I 1 6 YYMMDDI 1 2 YYI 3 4 MMI 5 6 DD

Multiple Occurrence Data Structure:A multiple-occurrence data structure is a data structure whose definition is repeated in a program to form a series of data structures with identical formats. You specify the number of occurrences of a data structure in positions 44 through 47 of the data structure statement.

116 of 150

Page 117: RPG400 Course Material

When positions 44 through 47 do not contain an entry, the data structure is not a multiple-occurrence data structure. All occurrences of a data structure have the same attributes and can be referred to individually. The OCUR operation code, which can only be used with a multiple-occurrence data structure, allows you to specify which occurrence of a data structure is used for subsequent operations within the program.

Note: Multiple occurrences are not allowed for a data area, file information, or program-status data structure.

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* I* I* A multiple-occurrence data structure is used to accumulate a I* series of totals for specific codes, and the totals of each of I* the occurrences of the data structure are written. I* The program-described data structure, TOTDS, has 99 occurrences I* (positions 46 and 47). The length of the data structure can be I* specified in positions 48 through 51. I* IDsname....NODsExt-file++.............OccrLen+......................* ITOTDS DS 99 I..............Ext-field+............PFromTo++DField+...............* I 1 50TOTCNT I 6 120TOT1 I 13 202TOT2 I* *.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* C* C* A numeric code field, CODE, contains a value of 01 though 99. C* This value is different each time the OCUR operation is processed. C* When the OCUR operation is processed, the CODE field is used to C* set the current occurrence of TOTDS. If the OCUR operation is C* successful, the program branches to the ADDRTN subroutine where C* a record count is made and input values are added to the data C* structure subfields. If the CODE field contains a value other C* than 01 through 99, indicator 25 is set on and the program C* branches to BADCOD. C* CL0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++* C CODE OCUR TOTDS 25 C 25 GOTO BADCOD C EXSR ADDRTN ________________ C " | Calculations | C " |________________| C BADCOD TAG C " ________________ C " | Calculations | C |________________|

117 of 150

Page 118: RPG400 Course Material

Data Areas :Data areas are objects used to transfer data to one or more programs within a job or between jobs. A Data area may be considered as a one-record Storage area .

A Data area can be of maximum 24 digits with maximum 9 decimal positions for *DEC type and for *CHAR type the maximum length is 2000 characters.

Created by CRTDTAARA, Modified by CHGDTAARA and Displayed by DSPDTAARA.

Data areas can be explicitly or implicitly retrieved and written.

Implicitly retrieved and written:

When the data area is defined in an RPG/400 program as a data area data structure, Its data is implicitly retrieved for processing and written back at the end the of the program.

I*IDsname....NODsExt-file++.............OccrLen+......................*IPARTNO UDSI..............Ext-field+............PFromTo++DField+...............*I 1 6 PARTNBRI*

Explicitly retrieved and written:

The Opcodes and reserved words related to the explicit processing of data are summarized as follows :OpCodes FunctionIN Explicitly retrieves a data area and optionally allows the programmer to

“lock” it so that it cannot be updated by another pgm during the execution of the controlling program.

OUT Explicitly updates the data area and unlocks it DEFN When used with *NAMVAR reserved word, It specifies that the Factor 2

entry is a data area.UNLCK Releases one or all the data areas locked by the controlling programReserved Words Function*LOCK Used in Factor 1 with opcode IN to lock a data area*NAMVAR Used in Factor 1 in opcode DEFN to define a data area

Used in Factor 2 in Opcode IN to access all data areas specified in the program

C* Data area assigned to a Field: CL0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++* C *NAMVAR DEFN CKINFO CHECKS 100 C IN CHECKS C*Example II C* RPG/400 Control to Change the value in Data area :

118 of 150

Page 119: RPG400 Course Material

CL0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++* C *NAMVAR DEFN CKINFO 10 C *LOCK IN CKINFO C MOVELCKINFO CHECK# 40 C MOVE CKINFO CKDATE 60 C MOVELCHECK# CKINFO C MOVE UDATE CKINFO C OUT CKINFO C UNLCKCKINFO C*Data area previously locked by an IN is automatically released from the locked C* state after the OUT statement is executed. If More than one data area is C* supported by the program, specifying UNLCK statement with *NAMVAR in factor 2 C* will unlock all of them at one time. On the other hand , if only a select data C* area is to be unlocked ,the data area name must be entered in Factor 2. C* C *NAMVAR UNLCK

119 of 150

Page 120: RPG400 Course Material

Data Structures For Exception/Error Control

Exception errors that cause program execution to cancel are not uncommon in the programming environment..Routines may be included in an RPG/400 program to identify and control exception/errors and prevent program execution “Aborts”.File Information Data structures and Program Status Data Structures are two RPG/400 run-time methods to control exception/error processing.

File Information Data Structures (INFDS):

A file information Data Structure provides exception/error information that may have occurred when processing a file during program execution.This type of data structure contains predefined subfields that identify:

The name of the file for which the error occurred. The record processed when the error occurred. The operation being processed when the error occurred. The status code number. The RPG/400 routine in which the error occurred.

Specifically, keywords including *FILE, *INP, *MODE, *OUT, *OPCODE, *SIZE, *STATUS, *RECORD, and *ROUTINE provide the previously named information for any file processed by the program.

The RPG/400 File Description and Input Specifications coding to support a File Information Data Structure(INFDS) is detailed in the below Figure. Note that a File Exception/Error Subroutine (INFSR) is specified on a second continuation statement which accesses the RPG/400 supplied *PSSR routine. When an error is detected,control will pass to this subroutine automatically.Based on the error type, programmer supplied statements in the *PSSR routine will determine the action to be taken (ie end the job or ignore error and continue with processing).

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* FINVPF IP E K DISK KINFDS INFDS1 F KINFSR *PSSR

. .

.

IINFDS1 DS I *FILE FILE I *OPCODE CODE I *STATUS STATUS I *RECORD RECORD I *ROUTINE ROUTIN

.

.

120 of 150

Page 121: RPG400 Course Material

.

C *PSSR BEGSR C STATUS IFEQ 01011 C MOVEL‘*GETIN’ READAG 6 C EXCPT ERROUT C ENDIF C ENDSRREADAG

The output generated in the *PSSR routine may be directed to any output device and include INFDS keyword values and/or programmer –supplied code.Some errors may require that execution of the program be cancelled.Under those circumstances *CANCL would be moved to READAG field and the program would end. In any case,INFDS exception/error control prevents the display of system supplied errors which would utilize system resources if a user response was not timely.

Note that the exception/error information for the keywords is only generated if the *STATUS keyword value is greater than 00099.

Program Status Data Structure:

Program Status Data Structures , however identify exceptions/errors that are generated in the program by RPG/400 operations and not by a file.

Note that any code greater than 00099 is flagged as an exception/error.Four key words *STATUS, *ROUTINE, *PARMS, AND *PROGRAM are supported by a Program Status Data Structure.

The eight character ROUTINE key word contains the name of the RPG/400 routine (eg: INIT,*GETIN,*DETL, *DETC, *TOTC, *TOTL , *OFL, *TERM , SR name, pgm name) in which the exception/error occurred. *PARMS is a three digit numeric keyword that stores the number of parameters passed to the program from a calling program. *PROGRAM is a 10-position character field that stores the name of the program in which the Program Status Data Structure is specified.

The below figure details the File Description and Input Specification syntax for a Program Status Data Structure.Instead of the RPG/400 *PSSR routine , a programmer named routine may be specified.

*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* FINVPF IP E K DISK KINFSR *PSSR

. .

.

I SDS I *FILE FILE I *OPCODE CODE I *STATUS STATUS I *RECORD RECORD

121 of 150

Page 122: RPG400 Course Material

I *ROUTINE ROUTIN...

C *PSSR BEGSR C STATUS IFEQ 01011 C MOVEL‘*GETIN’ READAG 6 C EXCPT ERROUT C ENDIF C ENDSRREADAG

122 of 150

Page 123: RPG400 Course Material

Chapter IX: RLU and Printer Files

Report Layout Utility (RLU)

RLU is one of the application development tools used to create and change report prototypes . RLU can be invoked either from the AS/400 command line through typing the command STRRLU or by selecting option ‘19’ from the WRKMBRPDM.

Report Line

A record that is part of the report prototype for which the user creates data descriptions specifications.

Report Prototype

A representation of the image of the report that a user builds on a display and the printed report image, both of which look like the actual listening created by the application program. The report prototype, when saved as a DDS source member, can be used to create a printer file, which in turn, can be used by an application program to create the report.

Printer File Keywords

There are in all over 45 keywords associated with printer files. These keywords are used to provide additional qualification to the printer file at various levels. Printer file keywords may be divided into the following groups:

File level keywords that are used at the file level and that would be common to all the record formats in the file.Record level keywords that are used at a particular record file level and that would be apply to all the constants and fields in the given record formats.Field Level keywords apply to particular field in a record format.

123 of 150

Page 124: RPG400 Course Material

Some of the commonly used keywords are detailed below.

File Level Keywords

REF Referenced FileUsed to specify a file that is to be referenced for all the subsequent referenced field definitions.

SKIPA Skip AfterUsed to specify at the file level to indicate that whenever a write operation is issued to a printer file, the printer is to skip to a specified line before printing the named record format.

SKIPB Skip BeforeUsed to specify at the file level to indicate that whenever a write operation is issued to a printer file, the printer is to skip to a specified line before printing the named record format.

CHRSIZ Character SizeUsed to specify a character size to all variables and constants in the named record format.

CPI Characters per InchUsed to specify the number of characters that are to be printed in a inch. The values specified must be valid for the printer used.

DRAWER Printer DrawerUsed to specify the drawer number from which stationery has to be selected for the printing of the named record format. This is used in situation where mail is printed with company letter heads, continuation sheets and envelopes being stacked in different stacks of a multi-drawer printer.

HIGHLIGHT HighlightUsed to specify that all variables and constants of the named record format are to be highlighted while being printed.

LPI Line per InchUsed to specify the number of lines allowable per inch of stationery while printing the named record format.

Record Level Keywords

PRTWLTY Print QualityUsed to specify the print quality to be used while printing the named record format.

SKIPA Skip After

124 of 150

Page 125: RPG400 Course Material

Used to specify at the record format level to indicate that whatever a write operation is issued to a record format, the printer is to skip to a specified line after printing the named record format.

SKIPB Skip BeforeUsed to specify at the record format level to indicate that whatever a write operation is issued to a record format, the printer is to skip to a specified line before printing the named record format.

SPACEA Space AfterUsed to specify at the record level to indicate that whenever a write operation is issued to a record format, the printer is to skip to a specified number of lines after printing the named record format.

SPACEB Space BeforeUsed to specify at the record level to indicate that whenever a write operation is issued to a record format, the printer is to skip to a specified number of lines before printing the named record format.

TEXT TextUsed to assign descriptive text to be associated with record format.

Field Level Keywords

REFFLD Referenced Field NameUsed to specify the name of previously defined field from the file indicator as the referenced file at the file level.

SKIPA Skip AfterUsed to specify at the field level to indicate that whenever a write operation is issued to a record format containing the field, the printer is to skip to a specified line after printing the named record format.

SKIPB Skip BeforeUsed to specify at the field level to indicate that whenever a write operation is issued to a record format containing the field, the printer is to skip to a specified line before printing the named record format.

(NOTE: The use of both SKIP keywords is not valid when specifying line numbers.)

125 of 150

Page 126: RPG400 Course Material

SPACEA Space AfterUsed to specify at the record level to indicate that whenever a write operation is issued to a record format, the printer is to skip to a specified number of line after printing the named record format.

SPACEB Space BeforeUsed to specify at the record level to indicate that whenever a write operation is issued to a record format, the printer is to skip to a specified number of lines before printing the named record format.

TEXT TextUsed to assign descriptive text to be associated with record format.

TIME TimeUsed to specify that the system time is to be retrieved and printed in the specified position.

Processing Printer Files in RPG Programs:

File Specifications:

In the RPG program the printer file is declared in the File specifications with the following definitions. Type of the file is ‘O’ for Output. Device is ‘PRINTER’

In the RPG calculation specification.Within the calculation specification there would be no reference to the printer file name. all references would be to the record formats defined in the printer file.

To write a particular record format, use one of the following opcodes.WRITE – for program-described printer files.

When writing printer file record formats always ensure that the current print line is less than the overflow line. Also ensure before writing a record format, that the enough number of lines available to be printed in a page.

Additional Recommended Reading Material1. SC09-1416-02 RLU Users Guide and Reference.

126 of 150

Page 127: RPG400 Course Material

Chapter X: Introduction To Control Language

Control language is used to string a group of system commands together to perform variety of system functions. By stringing together these commands we can execute these operations by merely invoking a program rather than execute a group of commands individually.

Command StructureA system command consists of three basic parts namely, the command name, parameter name and a parameter value. For example, in the following command,CRTDTAARA DTAARA(LIBA/ARA01) LEN(100) TYPE(*CHAR)The command, CRTDTAARA (Create Data Area) and the parameters with the corresponding values are

DTAARA LIBA/ARA01LEN 100TYPE *CHAR

When this command is executed, the parameters may be entered in any one of the following forms. Positional form, only the parameter values are entered or keyword form, both the parameter name and the corresponding parameter value are entered or both Positional and keyword form commands are entered.

Positional Form

When entering commands using only Positional entries, all the parameters used must be entered sequentially. For example, consider the following command.ADDAJE Add autostart job entry.

This command uses the three parameters which areSBSD Subsystem nameJOB Job nameJOBD Job Description name

These three parameters have been listed here in the sequence in which the command expects them. Therefore, using the Positional entry method of entering a command, we may execute the command as follows.

ADDAJE ABC DEF XYZwhere,

ABC is taken by the system as being the subsystem name

127 of 150

Page 128: RPG400 Course Material

DEF as being the job name, and XYZ as being the job description name.

Therefore, when using the positional entry method of entering a command, we must be very careful that the sequence in which we enter the parameter values is exactly the same sequence in which the system expects the values.

Keyword form

When entering commands using keyword entries, every parameter must be entered with the parameter name. For example, the add autostart job entry command (ADDAJE) may be entered as ,

ADDAJE SBSD(ABC) JOB(DEF) JOBD(XYZ)

Since the parameters are being entered with the parameter name and the parameter value, the sequence of the parameters may be changed. The same command would execute just the same even if it is entered as

ADDAJE JOB(DEF) JOB(XYZ) SBSC(ABC)

Both positional and Keyword form

Commands may be entered using a combination of both the Positional form and the keyword form. For example, consider the following command.

ADDCMNE Add communications entry

This command uses even seven parameters which are,SBSD Subsystem descriptionDEV Device nameRMTLOCNAME Remote location nameJOBD Job descriptionDFTUSR Default userMODE ModeMAXACT Maximum number of active jobs allowed

This command may be entered in the both form as follows.ADDCMNE ABC DEF XYZ MAXACT(2) DFTUSR(QPGMR)where,

ABC is taken by the system as being the subsystem nameDEF is being the device name

Delimiters

128 of 150

Page 129: RPG400 Course Material

Delimiters are special characters used to separate the various components of a CL statement. The following are valid CL delimiters.‘:’ Separates a command label from the command name like

LABEL:CRTPF FILE(LIBA/FILEA) RCDLEN(48)…‘’ Separates a command name from the command parameter and also separates the

various parameters of a command.() Are used to enclose parameter values‘/’ Separates the parts of a qualified name like LIBA/FILEA or RECFMT1/FLD001‘.’ or ‘,’ Used to indicate decimal point.‘ ’ Used to enclose string expressions, like TEXT(‘Customer Master File’)/* */ Used to enclose comments in a CL program like /* This is a test library*/

Command Continuation

Commands may be continued over one line with the use of a ‘-‘or ‘+’ sign. When used, either of these two characters are the last characters in the statement. The following examples illustrate the use of these characters as well as highlight the difference between these two characters.

CRTLIB LIB (TESTLIB) TEXT(‘This is a test-library’)

CRTLIB LIB (TESTLIB) TEXT(‘This is s test +library’)

Variable naming syntax

All variable within CL programs may be a maximum of 10 characters. Variable names may not include embedded blanks and must always begin with ‘&’.The second character must always be an alphabetic character. Valid examples of CL variable names are:

&FLDA&FLD001&A1

ConcatenationVariables and constants may be concatenated or stringed together for various reasons using any of the following syntax. The various methods of concatenation are:

1. *CAT represents as ||*CAT or || concatenates two variables or constants as they are.2. *BCAT represented as |>

129 of 150

Page 130: RPG400 Course Material

*BCAT or |> would strip out the trailing blanks of first string and insert one blank space. between the two components being concatenated.3. *TCAT represented as |<*TCAT or |< would strip out the trailing blanks of first string, then join that with the second string.

The following are the examples of the various types of concatenation discussed above.

&FLDA is defined as 5A and contains value ‘ABCDE’&FLDB is defined as 8A and contains value ‘1234 ‘

&FLDA *CAT ‘TEST01’ ‘ABCDTEST01 ‘&FLDA *BCAT &FLDB ‘ABCDE 1234 ‘&FLDB *TCAT ‘TEST01’ ‘1234TEST01’

Relational Expressions

The following are valid relational expressions allowed for use in CL programs.

1. = *EQ Equal to2. > *GT Greater than3. < *LT Less than4. >= *GE Greater than or equal to5. <= *LE Less than or equal to6. -| *NE Not equal to7. -|> *NG Not greater than8. -|< *NL Not less than

Logical Expressions

The following are valid logical expressions allowed for use in CL programs.

1. & *AND And2. | *OR Or3. -| *NOT Not

Substring expressions

130 of 150

Page 131: RPG400 Course Material

Parts of alphanumeric variables may be extracted using the substring function. A substring function may be used either as %SUBSTRING or %SST. The substring specifies the variable name, the starting position and the number of characters to be extracted. Consider the following example where &FLDA is defined as 8A and contains value ‘ABCD12345’.The substring expression

%SUBSTRING (&FLDA 4 3)

would extract 3 characters of the value of the variable &FLDA starting from position 4.Therefore, the result of this substring operation would be ‘D12’.

Using variable in a CL programAll variable in a CL program must be declared in the program using the DCL statement. The format of a DCL statement is as follows.

DCL VAR(&FLDA) LEN(10) TYPE(*CHAR)DCL VAR(&FLDB) LEN(6) TYPE(*DEC)DCL VAR(&FLDC) LEN(9 2) TYPE(*DEC)

A CL program may not address or use any variable that is not declared in the program.When used, DCL statements must immediately follow the PGM statement.

Using files in CL program

A CL program may use a maximum of one file of any type. This file is declared to the CL program using the DCLF file. The format of a DCLF statement is as follows:

DCLF FILE(FILEA)

The record format parameter RCDFMT of the declare file command may optionally be used to restrict the access of the program to only the named record format(s).If not mentioned, the program is allowed access to all the record formats in the file.

A DCLF statement must immediately follow the DCL statement (if a DCL statement is used) or the PGM statement and must always precede all other statements within the CL program.

Any variable defined in a file declared in a CL program need not be declared within the CL program using DCL statement. These variables can be addressed within the CL program using the ‘&’ naming convention for CL program variables.

131 of 150

Page 132: RPG400 Course Material

File Operations

The following are the only valid operations that can be performed on files in a CL program.

RCVF FILE(FILEA) Reads a record from the named fileSNDF FILE(FILEB) Writes a record from the named fileSNDRCVF DEV(*FILE) RECFMT(*FILE) Displays a record format from the display file for user input.(This operation is the equivalent of an EXFMT operation in a CL program)

Error Handling

All system errors encountered during the execution of a CL program can be trapped within a CL program with the use of a MONMSG statement. The MONMSG command can be executed at the program level or the command level. The placement of the MONMSG command determines whether it is a program level or command level MONMSG.

To implement the MONMSG command at the program level , we can code the MONMSG command immediately after the last DCL Statement or when there are no DCL statements, Immediately after the PGM statement.

To implement the MONMSG at the command level , we can code the MONMSG immediately after the command that we want to monitor.

We can monitor messages either specifically or generically.

Assigning Values

Variables can be assigned values – constants, variables or computed – using the change variable command CHGVAR. Some examples of CHGVAR command usage are

CHGVAR VAR(&FLDA) VALUE(‘ABCDE’)CHGVAR VAR(&FLDB) VALUE(‘&FLDB + 1)CHGVAR VAR(*INK25 ) VALUE(‘1’)CHGVAR VAR(&FLDC) VALUE((&FLDX + &FLDY) * &FLD2)

Logical Operations

The IF command can be used to perform logical operations.

IF COND(&FLDA *EQ ‘AB’) THEN(GOTO CMDLBL(OPEN))ELSE EXEC(CRTPG FILE(LIBA/FILEA) SRCFILE(LIBA/SRCFILEA)

132 of 150

Page 133: RPG400 Course Material

An ELSE statement may optionally be used with an IF statement

Additional Recommended Reading Material1. SC21-8077-2 Control Language: Programmer’s Guide-Vol I and II2. SC41-00300-02 Control Language: Reference – 3 Volumes

133 of 150

Page 134: RPG400 Course Material

Chapter XI: Open Query File Basics

OPNQRYF is the very powerful command that allows the programmer to select record dynamically based on variety of selection criteria (Including field mapping, groupings and the results of mathematical calculations).Depending on the selection criteria specified ,the OPNQRYF command may make use of existing file access paths to extract the desired data, or it may construct an access path of its own.

One crucial point to remember when using OPNQRYF is that you must use the SHARE(*YES) file attribute for each file opened by the OPNQRYF command. When you specify SHARE(*YES), subsequent opens of the same file will share the original open data path and thus see the file as presented by the OPNQRYF process. If OPNQRYF opens a file using the SHARE(*NO) attribute, the next open of the file will not use the open data path created by the OPNQRYF command, but instead will perform another full open of the file.

The following is a list of the major functions supplied by OPNQRYF.

Dynamic record selection Dynamic keyed sequence access path Dynamic keyed sequence access path over a join Dynamic join Handling missing records in secondary join files Unique-key processing Mapped field definitions Group processing Final total-only processing Improving performance Sort sequence processing

Open data Path(ODP) :

You write an RPG program to read it in the order in which the records were written to the file. This is called arrival sequence.

When you start the program, the system opens the file and makes it available to theProgram through an open data path. The open data path is, in this case, one that looks at the file in relative record number (RRN) sequence.

134 of 150

Page 135: RPG400 Course Material

An open data path, therefore, is the channel through which an application can access the records in a file. The same file could be used by another RPG program which is coded to read the file randomly by key. Since the key is used, the open data path uses the record keys - not the RRN's. In this case, therefore, we use a keyed sequence. Under most circumstances, the ODP can be thought of as the file itself, although in reality they are two entirely different concepts.

Let's use an example. Suppose a file consists of several records with a field called StateCode. If someone asked you to sort the file so you could show only records from California and ordered by Name, you could do this very easily in OPNQRYF. The ODP would point to only those records whose Code = "CA" and order them by a key called Name. We did not have to create a new file with records, simply use the ODP from the physical file and access the records thru CL. The ODP contains only pointers to the actual records in the physical file, indicating which records to retrieve and in what order. You can say that OPNQRYF creates a logical view over the physical file.

QRYSELECT

QRYSLT is the parameter that determines which records to include in the open data path created by OPNQRYF. It entails a series of comparisons joined with AND's and OR's - the kind of comparisons that reads "the amount due (contained in AMTDUE) is greater than $5000 and the last payment (LSTPMT) was at least 120 days old." QRYSLT, therefore sounds like it should receive a logical expression very much like the IF command's COND parameter:

IF COND(&AMTDUE *GT 5000 *AND &LSTPMT *GE 120)

You could try entering something like that in OPNQRYF's QRYSLT Parameter, removing the ampersands (&), but it won't work:

OPNQRYF QRYSLT(AMTDUE *GT 5000 *AND LSTPMT *GE 120)

The reason it doesn't work is because the QRYSLT parameter won't accept a logical value; it expects a character string. The correct way to code QRYSLT, therefore is:

OPNQRYF QRYSLT('AMTDUE *GT 5000 *AND LSTPMT *GE 120')

As you can see, the entire contents of QRYSLT must be enclosed in single quotes because QRYSLT requires a character value, and character values with embedded blanks must be enclosed in single quotes.Notice that numeric constants are not enclosed by two apostrophes (quotation marks).

When comparing a field value to a CL variable, use apostrophes as follows (only character CL variables can be used):

135 of 150

Page 136: RPG400 Course Material

If doing selection against a character, date, time, or timestamp field, specify: OPNQRYF FILE(FILEA) QRYSLT('"' *CAT &CHAR *CAT '" *EQ FIELDA')or, in reverse order: OPNQRYF FILE(FILEA) QRYSLT('FIELDA *EQ "' *CAT &CHAR *CAT '"')Notice that apostrophes and quotation marks enclose the CL variables and *CAT operators.

If doing selection against a numeric field, specify: OPNQRYF FILE(FILEA) QRYSLT(&CHARNUM *CAT ' *EQ NUM')or, in reverse order: OPNQRYF FILE(FILEA) QRYSLT('NUM *EQ ' *CAT &CHARNUM);Notice that apostrophes enclose the field and operator only.

Steps involved in a typical OPNQRYF program:

1. Begin with an Override Database File (OVRDBF) command, specifying SHARE(*YES). If necessary, add other overrides as your application requires, such as, overriding to a member other than *FIRST.

2. Specify the OPNQRYF command with the parameters

3. Call your RPG program/any HLL Program that processes the file. The HLL program should be coded as if it were going to process the entire file, without any provisions for record selection or ordering, since OPNQRYF has already done this job.

4. Call the Close File (CLOF) command.

5. Call the Delete Override (DLTOVR) command to remove the overrides created by step #1.

Example:PGM

DCL VAR(&YEAR) TYPE(*CHAR) LEN(2)RTVSYSVAL SYSVAL(QYEAR) RTNVAR(&YEAR)OVRDBF FILE(ORDMST) TOFILE(JANELIB/ORDMST) SHARE(*YES)

OPNQRYF FILE ((ORDMAST)) QRYSLT(‘(OCODE *NE “D”) *AND +(“’ *CAT &YEAR *CAT ‘” *EQ %SST(DATE 5 2))’) +KEYFLD((OVENDR) (OINAME)) +MAPFLD((DATE ‘%DIGITS(ODATE)’))

CALL PGM(ORDRPT2) //Processing Program

CLOF OPNID(ORDMST)DLTOVR FILE(ORDMST)

ENDPGM

136 of 150

Page 137: RPG400 Course Material

Additional Recommended Reading Material1. DB2 UDB for AS/400 Database Programming

137 of 150

Page 138: RPG400 Course Material

Chapter XII: Message Subfiles in RPG

Message Subfiles

Message subfiles are special subfiles designed to hold messages. Message subfiles have some unique properties that make them very useful. They load themselves automatically from messages on a given program message queue. Message subfiles also allow users to view the second-level help text associated with a message, without any additional programming effort. Message subfiles make it possible to setup a consistent set of information, warning, or error messages in a message file for a given program or application, and to display those messages to the user with the greatest of ease. With just a little direction from your RPG and DDS, message subfiles pretty much take care of themselves.

Steps Involved :

Set up a message file (*MSGF) containing the messages you want to use in your application. You can use an existing message file or create your own. You should not usually modify system-supplied message files, such as QCPFMSG. Message files are created with the CRTMSGF command. New messages can be added via the ADDMSGD command or the WRKMSGF command.

Define a message subfile in your display file.

Code your application program to send program messages to the program message queue. The best way to accomplish this in RPG is to use the QMHSNDPM (Send Program Message) API. You can also use the SNDPGMMSG command, but the best place to use that command is in a CL program.

After displaying the message subfile, clear the messages from the program message queue using the QMHRMVPM (Remove Program Message) API.

For every call stack entry, which can be an OPM program or an ILE procedure, there exists a corresponding program message queue with the same name. I created my own message file, but you can certainly use the system-supplied messages and plug in your own text. For instance, if users are accustomed to seeing message ID CPF9898 from the system-supplied message file, QCPFMSG, as being something serious, you could still use

138 of 150

Page 139: RPG400 Course Material

that message ID and substitute your own message. This doesn't mean you change the CPF9898 message in the actual message file. You simply override the message text in your program. If there are substitution parameters associated with a specific message, you can also fill in those parameters using the program message APIs. If message files aren't your bag, you can also send text messages to the program message queue and use no message file at all. Let's look at some code.

Example :

The DDS example, consists of three record formats: SCREEN1, MSGSFL, and MSGCTL. FMT1 is the primary screen, and it allows the user to enter data. As you will see in the RPG, this data isn't going anywhere; its purpose is purely to demonstrate how to use a message subfile. MSGSFL is the message subfile record format, and MSGCTL is the control format for MSGSFL. These formats work much the same way as regular subfile control and record formats. There are, however, some differences between regular subfiles and message subfiles.

With regular subfiles, you have to handle the loading and clearing in your program. Typically, in your RPG program, you will set on the indicator used to condition the SFLCLR keyword in your DDS, write to the subfile control format, and set off the indicator to get ready to load and display. With message subfiles, you don't explicitly clear the subfile in your program; rather, you link the subfile to a program message queue and remove messages from that message queue. This, in essence, clears the subfile.

This same theory holds true for loading the subfile. When displaying subfile records in a regular subfile, you must first execute some sort of load routine. This routine usually consists of a DO loop that reads records from a database file and writes them to the subfile record format. Message subfiles will have none of that. By linking the message subfile to a specific program message queue and sending messages to that queue, the message subfile will automatically load itself with records from the program message queue. Message subfiles require the use of several special DDS keywords, listed below.

In the message subfile record format, the following keywords are required:

SFLMSGRCD is used to set the starting line on the display for the message subfile. In most cases it is set to 24 (the bottom line of the display), but you could display more than one message at a time, in which case you would set this parameter accordingly.

SFLMSGKEY controls the message key of the first message that is to be displayed in the message subfile. Every message on a message queue has a unique message key that is

139 of 150

Page 140: RPG400 Course Material

assigned as the message arrives on the message queue. In certain cases, you may wish to maintain old messages on the queue and only display messages from a certain point forward in the message subfile. Setting the message key allows you to control which messages are displayed.

SFLPGMQ controls which program message queue the messages are pulled from. In my example, it is being populated with the name of the program from the program status data structure in the RPG program or We can explicitly pass the Program name. This technique allows you to easily copy the message subfile record formats into a new display file, with no changes required to the display file. Of course, the PGMQ field must be declared .

When in a message subfile, SFLCTL, SFLSIZ, SFLPAG, SFLDSP, SFLEND, and SFLDSPCTL behave normally, except that SFLDSP and SFLDSPCTL must be used without conditioning indicators. Also, SFLPAG must be at least one less than SFLSIZ in a message subfile; they cannot be equal. Message subfiles are considered load-all subfiles. Notice also that I don't use the *MORE parameter on my message subfile. The reason is, using the *MORE parameter causes "More..." and "Bottom" to display one line under the last line on the display. Since I am using line 24, which is the last possible line on the display, I would get an error if I tried to use the *MORE parameter. The plus sign (+) works for me, but if you're dying to use *MORE with your message subfiles, try starting on line 23--SFLMSGRCD(23)--and keeping SFLPAG as 1. Then you won't get an error.

Let's look at the differences in the way SFLINZ keyword behave when it is in a message subfile.

SFLINZ, in the case of a message subfile, causes the system to automatically load the subfile with messages from the message queue specified. This is different from its use with regular subfiles. In regular subfiles, SFLINZ loads the subfile with the number of records indicated by SFLSIZ and sets the fields to their default values.

DDS Source:

******************************************************************     A                                      CF03(03)     A                                      HELP     A          R FMT1     A                                      OVERLAY     A                                  2  3'FULL SCREEN'     A            FLD1          10   B  3  3      *

    A          R MSGSFL                    SFL* Message subfile record

* SFLMSGRCD controls which line the message subfile starts on. * SFLMSGKEY controls the message key of the message that is to * be the first one displayed. * SFLPGMQ controls which program message queue messages are pulled from.

140 of 150

Page 141: RPG400 Course Material

*

    A                                      SFLMSGRCD(24)     A            MSGKEY                    SFLMSGKEY     A            PGMQ                      SFLPGMQ * Message subfile control record * SFLPAG > SFLSIZ to allow the system to control page up and down * in the subfile. The subfile will be automatically extended * based on the number of entries in the program message queue. * SFLDSP and SFLDSPCTL cause the subfile and control record to be * displayed when the control format is thrown * SFLINZ, in this case, causes the system to automatically load * the subfile with messages from the message queue specified * SFLPGMQ controls which program message queue messages are pulled from * SFLEND with indicators that always evaluate to TRUE, allows the * system to automatically toggle the "+" sign that indicates if * there are more records to display in the subfile.

    A          R MSGSFLC                   SFLCTL(MSGSFL)     A                                      SFLSIZ(0002)     A                                      SFLPAG(0001)     A                                      OVERLAY     A                                      SFLDSP     A                                      SFLDSPCTL     A                                      SFLINZ     A  98                                  SFLEND     A            PGMQ                      SFLPGMQ *****************************End of Data*************************************

RPG Source: **************************************************************************

    FFS2       CF   E             WORKSTN *constant for the message     I 'FILE LIBRARY 'C MSGCNS      *         * SEND MSG0003 FROM MESSAGE FILE XZY1337 TO PROGRAM MESSAGE QUEUE     C                   MOVEL     'MSG0003'     MSGID     C                   MOVEL     'XZY1337'     MSGF     C                   MOVE      MSGCNS        MSGDTA 62     C                   MOVE      'I'           MSGOPT     C                   EXSR      SEND

     *

     * SEND MSG0001 FROM MESSAGE FILE XZY1337 TO PROGRAM MESSAGE QUEUE

    C                   MOVEL     'MSG0001'     MSGID     C                   MOVEL     'XZY1337'     MSGF     C                   MOVE      'I'           MSGOPT     C                   EXSR      SEND

     *

     * SETON SFLEND INDICATOR FOR MESSAGE SUBFILE

    C                   SETON                                        98

     * WRITE MESSAGE SUBFILE

    C                   WRITE     MSGSFLC

     * WRITE/READ REGULAR SCREEN FORMAT

    C                   EXFMT     FMT1

141 of 150

Page 142: RPG400 Course Material

     * CLEAR THE PROGRAM MESSAGE QUEUE

    C                   MOVE      'C'           MSGOPT     C                   EXSR      SEND

     *

     * WRITE MESSAGE SUBFILE

    C                   WRITE     MSGSFLC

     * WRITE/READ REGULAR SCREEN FORMAT

    C                   EXFMT     FMT1     C                   MOVE      '1'           *INLR

     ****************************************************************

    C     *INZSR        BEGSR

     * MOVE THE PROGRAM NAME TO THE PROGRAM MESSAGE QUEUE FIELD

    C                   MOVEL     'MSGSFLPG'    PGMQ     C                   MOVE      'M '          PGMQ

    C                   ENDSR

     ****************************************************************

     * THIS SUBROUTINE CALLS A CL PROGRAM THAT SENDS THE MESSAGE

     * TO THE PROGRAM MESSAGE QUEUE.

     ****************************************************************

    C     SEND          BEGSR

    C                   CALL      'SENDPGM'     C                   PARM                    MSGID             7     C                   PARM                    MSGF             10     C                   PARM                    MSGDTA           62     C                   PARM                    MSGOPT            1     C                   ENDSR*****************************End of Data*************************************

CL Program to Send Messages:

**************************************************************************

         PGM        PARM(&MSGID &MSGF &MSGDTA &MSGOPT)             DCL        VAR(&MSGID) TYPE(*CHAR) LEN(7)             DCL        VAR(&MSGF) TYPE(*CHAR) LEN(10)             DCL        VAR(&MSGOPT) TYPE(*CHAR) LEN(1)             DCL        VAR(&MSGDTA) TYPE(*CHAR) LEN(62)

            IF         COND(&MSGOPT *EQ 'I') THEN(SNDPGMMSG +                          MSGID(&MSGID) MSGF(&MSGF) MSGDTA(&MSGDTA))

          IF         COND(&MSGOPT *EQ 'C') THEN(RMVMSG PGMQ(*PRV +                          (*)) CLEAR(*ALL))*****************************End of Data*************************************

USING APIs instead of a CL:

142 of 150

Page 143: RPG400 Course Material

**************************************************************************

* * Send message subroutine * c sndmsg begsr

c call 'QMHSNDPM' c parm msgId c parm msgLoc c parm msgRplDta c parm msgRplDtaLen c parm msgType c parm msgQueue c parm msgCallStack c parm msgKey c parm msgErr

c endsr

*************************************************************** * Remove message subroutine *************************************************************** c rmvmsg begsr * c call 'QMHRMVPM' c parm msgQueue c parm msgCallStack c parm msgKey c parm msgRmv c parm msgErr

**************************************************************************

143 of 150

Page 144: RPG400 Course Material

Appendix A : RPG Opcodes

Operation codes in RPG/400Codes Factor 1 Factor 2 Result Field Resulting Ind.ACQ QRGRCOP

PWORKSTN file

- ER -

ADD(1/2) Addend Addend Sum + - ZANDxx Comparand ComparandBEGSR Subroutine

nameBITOF Bit numbers Character fieldBITON Bit numbers Character fieldCABxx Comparand Comparand Label HI LO EQCALL Program

NamePLIST name -- ER LR

CASxx Comparand Comparand Subroutine Name

HI LO EQ

CAT (p) Source String 1

Source String 2:Number of Blanks

Target String

CHAIN(n) Search argument

File name Data Structure NR ER --

CHECK Comparator String

Base String : start

Left most Position

-- ER FD

CHECKR(2) Comparator String

Base String : start

Right most Position

-- ER FD

CLEAR *NOKEY Structure or Variable

CLOSE File Name -- ER --COMIT Boundary -- ER --COMP(1) Comparand Comparand HI LO EQDEBUG Identifier Output file Debug

InformationDEFN *LIKE Referenced

fieldDefined field

DEFN *NAMVAR

Internal program area

External data area

DELET Search Argument

File name NR ER --

144 of 150

Page 145: RPG400 Course Material

DIV (1/2) Dividend Divisor Quotient + - ZDO Starting

ValueLimit Value Index Value

DOUxx Comparand ComparandDOWxx Comparand ComparandDSPLY Message

identifierOutput queue Response -- ER --

DUMP IdentifierELSEEND Increment

ValueENDCSENDDO Increment

ValueENDIFENDSLENDSR Label Return pointEXCPT EXCPT Name

Codes Factor 1 Factor 2 Result Field Resulting Ind.EXFMT Record format

name-- ER --

EXSR Subroutine name

FEOD File name -- ER --FORCE File nameFREE Program

name-- ER --

GOTO LabelIfxx Comparand ComparandIN *LOCK Data area

name-- ER --

ITERKFLD Key FieldKLIST KLIST nameLEAVELOKUP (1)(Array)

Search argument

Array name HI LO EQ

LOKUP (1)(Table)

Search argument

Table name Table name HI LO EQ

MHHZO Source field Target fieldMHLZO Source field Target field

145 of 150

Page 146: RPG400 Course Material

MLHZO Source field Target fieldMLLZO Source field Target fieldMOVE (p) Source field Target field + - ZBMOVEA (P) Source Target + - ZBMOVEL Source field Target field + - ZBMULT (1/2) Multiplicand Multiplier Product + - ZMVR Remainder + - ZNEXT Program

DeviceFile name - ER -

OCCUR Occurrence Value

Data Structure Occurrence Value

- ER -

OPEN File Name - ER -ORxx Comparand ComparandOTHEROUT *LOCK Data area

name- ER -

PARM Target field Source field ParameterPLIST PLIST namePOST (3) Program

deviceFile name INFDS name - ER -

READ (n) File name, Record name

Data Structure - ER EOF

READC (n) Search argument

File name, Record name

Data Structure - ER EOF

READE (n) Search argument

File name, Record name

Data Structure - ER EOF

READP (n) File name, Record name

Data Structure - ER BOF

REDPE (n) Search argument

File name, Record name

Data Structure - ER BOF

REL Program device

File name - ER -

RESET *NOKEY Structure or Variable

146 of 150

Page 147: RPG400 Course Material

Codes Factor 1 Factor 2 Result Field Resulting Ind.RETRNROLBK - ER -SCAN (2) Comparator

string : length

Base string : start

Left-most position

- ER FD

SELECSETGT Search

argumentFile name NR ER -

SETLL Search argument

File name NR ER EQ

SETOF (1) OF OF OFSETON (1) ON ON ONSHTDN ON - -SORTA Array nameSQRT (1/2) Value RootSUB (1/2) Minuend Substrhend Difference + - ZSUBST (p) Length to

extractBase string : start

Target String - ER -

TAG Label TESTB (1) Bit numbers Character field OF ON EQTESTN (1) Character field NU BN BLTESTZ (1) Character fieldTIME Numeric fieldUNLCK Data area,

record or file name

- ER -

UPDAT File name Data structure - ER -WHxx Comparand ComparandWRITE File name Data structure - ER EOFXFOOT (1/2) Array name Sum + - ZXLATE (P) From :To String :start Target String - ER -Z-ADD Addend Sum + - ZZ-SUB Subtrahend Difference + - Z

Legend:

(1) At least one resulting indicator required.(2) A found indicator is required if the result field is not specified.(3) You must specify factor 2 or the result field. You may specify both.(P) Pad the result with blanks. (1/2) Half adjust the result.

147 of 150

Page 148: RPG400 Course Material

(n) No lock.

148 of 150

Page 149: RPG400 Course Material

Appendix B : AS/400 Data Limits

AS/400 Data limits:

Bytes in one record 32,766

Fields per record 8,000

Key fields in one record 120

Keysize in bytes 256

Records in one file 16,777,215

Bytes in one file 2,147,483,648

Database size size of disk storage

Logical Files (Views) from one physical file 3,686

Physical files used in one Logical File (View) 32

Maximum files in a JOIN 32

Maximum field size in bytes 32,766

Maximum decimal number 9,999,999,999,999,999,999,999,999,999,999

149 of 150

Page 150: RPG400 Course Material

Appendix C : RPG/400 Restrictions

Function RestrictionAN/OR lines (positions 7 and 8 of calculation specifications)

Maximum of 7 per operation.

Arrays and tables Maximum of 200 per program.Array/table input record length for compile time Maximum length is 80.Character field length Maximum length is 256.Control fields (position 59 and 60 of input specifica-tions) length

Maximum length is 256.

Data structure length Maximum of 9999.Data structure occurrences (number of) Maximum of 9999 per data structure.Edit Word Maximum length of 24 for literals or 115 for named

constants.Elements in an array/table (positions 36 through 39 of extension specifications)

Maximum of 9999 per array/table.

File Maximum of 50 per program.Levels of nesting in structured groups Maximum of 100.Look-ahead Can be specified only once for a file. Can be specified

only for primary and secondary files.Named Constant Maximum length of 256 for character named constant,

512 for hexadecimal named constant, and 30 digits with 9 decimal positions for numeric named constant.

Overflow indicator Only 1 unique overflow indicator can be specified per printer file.

Parameters Maximum of 255Primary file (P in position 16 of file description specifi-cations)

Maximum of 1 per program.

Printer file (PRINTER in positions 40 through 46 of file description specifications)

Maximum of 8 per program.

Printing lines per page Minimum of 2; maximum of 112.Program status data structure Only 1 allowed per program.Record address file (R in position 16 of file description specifications)

Only 1 allowed per program.

Record length for program described file (positions 24 through 27 of file description specifications)

Maximum length is 9999.

Structured groups (see levels of nesting)

Subroutines Maximum of 254 per program.Tables (see arrays)

Any device record size restraints override this value.

150 of 150