You are on page 1of 148

Table of Contents: Chapter I :AS/400 Highlights..................................................................................

7
Introduction :................................................................................................................................7 Technology-Independent Machine Interface ..........................................................................7 Operating System OS/400 .......................................................................................................8 Single-Level Storage ...............................................................................................................8 Logical Partitioning (LPAR) ...................................................................................................9 Objects.....................................................................................................................................9 AS/400 Processing Environment...............................................................................................12 What is a job?.......................................................................................................................12 Job Description:.....................................................................................................................12 Subsystem..............................................................................................................................12 Job Queues.............................................................................................................................12 Output Queues.......................................................................................................................12 Type of Jobs...........................................................................................................................12 AS/400 Security.........................................................................................................................14 Security at object level:..........................................................................................................14 Security Functions.................................................................................................................15 Security Levels.......................................................................................................................16 Application Development Tools (ADT)....................................................................................17 Program Development Manager (PDM)................................................................................17 Source Entry Utility (SEU)....................................................................................................20 Data File Utility (DFU)..........................................................................................................20

Chapter II –Libraries...........................................................................................22
Library Categories.....................................................................................................................22 Library List:..............................................................................................................................23 Library commands:....................................................................................................................23 Library List Commands:............................................................................................................23

Chapter III: AS/400 Database ............................................................................24
File Types:.................................................................................................................................24 Database Files:...........................................................................................................................25 Access paths:..........................................................................................................................25 Physical Files:........................................................................................................................26 Logical Files:.........................................................................................................................27 Types Of Logical Files...........................................................................................................28 Join Logical File....................................................................................................................28 Non - Join Logical File:.........................................................................................................28 Field Reference Files:................................................................................................................29 Importance of using Field Reference Files............................................................................29 Naming Conventions.................................................................................................................29

Chapter IV: Data Description Specification (DDS)...........................................31
Defining Physical Files..............................................................................................................31 Components of DDS..............................................................................................................32 Physical File Keywords.........................................................................................................33 File Level Keywords..............................................................................................................33 1 of 148

Record Level Keywords........................................................................................................33 Field Level Keywords............................................................................................................33 Key Field Level Key words...................................................................................................35 Defining Logical Files...............................................................................................................36 Logical file Keywords...........................................................................................................37 File Level Keywords..............................................................................................................37 Record Level Keywords ......................................................................................................38 Join Logical Files...................................................................................................................39 Join Level Keywords .....................................................................................................40 Examples of database files in DDS:...........................................................................................41 Example of a field reference file:...........................................................................................41 Example of a physical file with a new record format:...........................................................42 Example of a logical file specifying multiple formats and new keys:...................................43 Example of a logical file specifying a new record format:....................................................43 Example of a join logical file:................................................................................................44 DDM Files.................................................................................................................................45

Chapter V: SDA and Display Files......................................................................46
Screen Design Aid(SDA):..........................................................................................................46 Adding fields..........................................................................................................................48 Adding constants ...................................................................................................................48 Adding fields from a database file.........................................................................................48 Moving, Copying and Shifting fields.....................................................................................49 Date and Time keywords.......................................................................................................49 Display Files:.........................................................................................................................50

Chapter VI: RPG/400...........................................................................................57
RPG/400 Language Concepts....................................................................................................57 RPG/400 Specifications.............................................................................................................58 H CONTROL SPECIFICATION......................................................................................59 F FILE SPECIFICATION.................................................................................................59 E EXTENSION SPECIFICATION....................................................................................59 L LINE COUNTER SPECIFICATION.............................................................................59 I INPUT SPECIFICATION..............................................................................................59 C CALCULATION SPECIFICATION.............................................................................59 O OUTPUT SPECIFICATION.........................................................................................59 RPG/400 Operation Codes (OPCODES):..................................................................................59 Arithmetic Operations............................................................................................................60 ADD (Add Statement)......................................................................................................60 Z-ADD (Zeroise and add).............................................................................................60 SUB (Subtract statement)..................................................................................................61 Z-SUB (Zeroise and subtract)............................................................................................61 MULT (Multiply)..............................................................................................................61 DIV (Divide)......................................................................................................................62 MVR (Move remainder)...................................................................................................62 SQRT (Square root)..........................................................................................................62 Move Operations:...................................................................................................................62 MOVE (Move)..................................................................................................................62 2 of 148

MOVEL (Move left)..........................................................................................................63 Compare Operations..............................................................................................................63 IFxx (If condition).............................................................................................................64 DOUxx (Do until)..............................................................................................................65 DOWxx (Do while)............................................................................................................65 WHxx (When)....................................................................................................................66 COMP (Compare)..............................................................................................................66 Declarative Operations...........................................................................................................67 PLIST ( Parameter list)......................................................................................................67 PARM (Parameter)...........................................................................................................67 KFLD (Key Field).............................................................................................................67 KLIST (Key list)................................................................................................................67 DEFN (Definition).............................................................................................................68 TAG(Tag)..........................................................................................................................68 Initialization Operations.........................................................................................................68 CLEAR (Clear)..................................................................................................................68 RESET (Reset)...................................................................................................................69 String Operations..................................................................................................................69 CAT (Concatenate Two Character Strings).......................................................................69 CHECK (Check Characters)..............................................................................................70 CHEKR (Check Reverse)..................................................................................................70 SCAN (Scan Character String)..........................................................................................71 XLATE (Translate)............................................................................................................71 SUBST (Substring)............................................................................................................72 Subroutine Operations...........................................................................................................72 CASxx (Compare and execute subroutine)........................................................................72 EXSR(Execute Subroutine)...............................................................................................73 BEGSR(Begin Subroutine)................................................................................................73 ENDSR(End Subroutine)...................................................................................................73 Indicator Operations...............................................................................................................74 SETON (Set on indicator)..................................................................................................74 SETOF (Set off indicator)..................................................................................................74 Structured Programming Operations.....................................................................................74 ORxx (Or condition)..........................................................................................................74 ANDxx (And condition)....................................................................................................75 ELSE (Else).......................................................................................................................75 END (End).........................................................................................................................75 ENDyy (End Condition)....................................................................................................75 DO (Do Iteration)...............................................................................................................76 SELEC (Select)..................................................................................................................76 OTHER (Other)................................................................................................................77 ITER (Iterate) ....................................................................................................................77 LEAVE (Leave).................................................................................................................77 File Operations .....................................................................................................................78 OPEN (Open File for Processing)......................................................................................78 CLOSE (Close Files).........................................................................................................78 3 of 148

SETLL (Set Lower Limits)................................................................................................79 SETGT (Set Greater Than)................................................................................................80 READ (Read a Record).....................................................................................................80 READE (Read Equal Key)................................................................................................80 READP(Read a Previous Record)....................................................................................81 REDPE (Read Prior Equal)................................................................................................81 CHAIN (Random Retrieval from a File)...........................................................................82 WRITE (Create New Records)..........................................................................................82 UPDAT (Modify Existing Record)....................................................................................82 DELET (Delete Record)....................................................................................................83 Calling Operations.................................................................................................................83 CALL (Call a Program).....................................................................................................83 PARM (Identify Parameters).............................................................................................84 PLIST (Identify a Parameter List)....................................................................................85 Branching Operations............................................................................................................86 GOTO(Go to).....................................................................................................................86 ITER (Iterate).....................................................................................................................86 LEAVE (Leave).................................................................................................................86 Array Operations....................................................................................................................86 MOVEA (Move array).......................................................................................................86 XFOOT (Array Total)........................................................................................................87 LOKUP (Lookup)..............................................................................................................87 SORTA (Sort array)...........................................................................................................88 Data Area Operations.............................................................................................................88 Commitment Control Operations...........................................................................................88 COMIT (Commit)..............................................................................................................88 ROLBK (Roll Back)..........................................................................................................88 Examples For File processing:...................................................................................................89 RPG syntax to process an externally defined Physical File:...............................................89 RPG syntax to process a Program defined Physical File:...................................................89

Chapter VII: Subfiles ..........................................................................................91
Components of Subfile..............................................................................................................91 Subfile Data Description Specification : .................................................................................93 Handling Subfiles in RPG Programs.........................................................................................94 Multi page subfiles:....................................................................................................................95 Subfile Load Options- Pros and Cons....................................................................................95 Load all Subfile:.....................................................................................................................95 ...........................................................................................................................................96 Expanding Subfile:.................................................................................................................98 Single Page Subfile:.............................................................................................................100 Fold and Drop capabilities :.....................................................................................................102 Other interesting Subfile Keywords:...................................................................................103 Additional Recommended Reading Material.......................................................................103

Chapter VIII: Arrays, Tables and Data structures...........................................104
Arrays: ....................................................................................................................................104 Array Description :..............................................................................................................104 4 of 148

Loading of an array:.................................................................................................................105 Compile time array:.............................................................................................................105 Prerun time Array:...............................................................................................................106 Run time array:....................................................................................................................107 Searching Arrays......................................................................................................................109 Searching an Array without an Index..................................................................................109 Searching an Array with an Index.......................................................................................110 Specifying an Array in Calculations........................................................................................111 Tables :.....................................................................................................................................113 Data Structures: .......................................................................................................................113 Format of Data Structure Subfields in Storage:...................................................................113 Data Structure Statement Specifications:.............................................................................114 Examples:.............................................................................................................................115 Multiple Occurrence Data Structure:...................................................................................116 Data Areas :..............................................................................................................................117 Implicitly retrieved and written:.........................................................................................117 Explicitly retrieved and written: ......................................................................................117 Data Structures For Exception/Error Control..........................................................................119 File Information Data Structures (INFDS):.........................................................................119 Program Status Data Structure:............................................................................................120

Chapter IX: RLU and Printer Files...................................................................122
Report Layout Utility (RLU)...................................................................................................122 Report Line..........................................................................................................................122 Report Prototype..................................................................................................................122 Printer File Keywords..........................................................................................................122 Processing Printer Files in RPG Programs:.........................................................................125

Chapter X: Introduction To Control Language ...............................................126
Command Structure.................................................................................................................126 Positional Form....................................................................................................................126 Keyword form......................................................................................................................127 Both positional and Keyword form......................................................................................127 Command Continuation.......................................................................................................128 Variable naming syntax.......................................................................................................128 Concatenation......................................................................................................................128 Relational Expressions.........................................................................................................129 Logical Expressions.............................................................................................................129 Substring expressions...........................................................................................................129 Using variable in a CL program...........................................................................................130 Using files in CL program...................................................................................................130 File Operations.....................................................................................................................130 Error Handling.....................................................................................................................131 Assigning Values.................................................................................................................131 Logical Operations...............................................................................................................131

Chapter XI: Open Query File Basics................................................................133
Open data Path(ODP) : ...........................................................................................................133 QRYSELECT..........................................................................................................................134 5 of 148

Steps involved in a typical OPNQRYF program:....................................................................135 Example:................................................................................................................................135

Chapter XII: Message Subfiles in RPG............................................................136
Message Subfiles ....................................................................................................................136 Steps Involved : ...................................................................................................................136 Example :.............................................................................................................................137

Appendix A : RPG Opcodes.................................................................................142 Appendix B : AS/400 Data Limits.......................................................................147 Appendix C : RPG/400 Restrictions....................................................................148

6 of 148

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 148

As soon as they made this transition, customers had 64-bit application programs that ran on a 64bit 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. 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 8 of 148

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 nway 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 Library- that which contains addressability to the object

9 of 148

• • • • • • • •

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 Objects CMD 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 DTAQ FILE JOBD JOBQ Data area : Data Queue File Job desription Information describing environment in which a job would be executed A data store

Job Queue Queue 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 Library User defined place within the system where any particular group of objects reside.

10 of 148

MSGF MSGQ OUTQ PGM

Message File A database file where messages are stored. Message Queue Queues where messages wait to be passed or displayed. Output Queue Queue where the system output waits to be viewed printed or transferred Program

11 of 148

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 number Job 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 148

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 148

AS/400 Security
The 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 148

• •

*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 system The 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 148

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 10 The 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 20 The 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 30 The 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 40 The 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 148

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 148

Invoking PDM Program 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 menu 2. 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 F12=Cancel F4=Prompt F9=Retrieve F18=Change defaults F10=Command entry (C) COPYRIGHT IBM CORP. 1981, 2000.

18 of 148

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 3=Copy 9=Save 5=Display 10=Restore 7=Rename 12=Work with ...

Type options, press Enter. 2=Change 8=Display description Opt Library RBTSYSLIB QSYS QSYS2 QHLPSYS QUSRSYS SYSTEM XCOM2 QMQM QSYS2924 Type *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS *PROD-SYS

Text ROBOT SYSTEM LIBRARY SYSTEM LIBRARY SYSTEM LIBRARY FOR CPI'S System Library for Users EHQ System Software CA-XCOM software library MQSERIES FOR AS/400

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 . . . . . 4=Delete 9=Save Attribute PF-DTA PF-DTA PF-DTA LF LF LF LF LF 5=Display 10=Restore ________________ ________________

Type options, press Enter. 2=Change 3=Copy 8=Display description Opt Object XMSGDTARFP YABOABARFP YABOABAXXP YABOABA00L YABOABA01L YABOABA02L YABOABA03L YABOABA04L Type *FILE *FILE *FILE *FILE *FILE *FILE *FILE *FILE

7=Rename 11=Move ...

Text MDL Message Physica yaboabarfp Physical fi Contains YABOABARFP deleted model dat MDL Abo update (@@ABOABA) MDL Abo action rtv (@@ABO/@@CHC/@@ABO MDL Abo action rtv (@@ABO/@@ABOABA_P) MDL Abo action rtv (@@ABO/@@REFCND > 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 148

Work with Objects Using PDM Library . . . . . TSTLIB Position to . . . . . . . . ___________ Position to type . . . . . _____________ 4=Delete 9=Save Attribute PF-DTA PF-DTA PF-DTA LF LF LF LF LF 5=Display 10=Restore 7=Rename 11=Move ...

Type options, press Enter. 2=Change 3=Copy 8=Display description Opt Object XMSGDTARFP YABOABARFP YABOABAXXP YABOABA00L YABOABA01L YABOABA02L YABOABA03L YABOABA04L Type *FILE *FILE *FILE *FILE *FILE *FILE *FILE *FILE

Parameters or command ===>______________________________________________________________________________ F3=Exit F4=Prompt F5=Refresh F6=Create F9=Retrieve

Text MDL Message Physica yaboabarfp Physical fi Contains YABOABARFP deleted model dat MDL Abo update (@@ABOABA) MDL Abo action rtv (@@ABO/@@CHC/@@ABO MDL Abo action rtv (@@ABO/@@ABOABA_P) MDL Abo action rtv (@@ABO/@@REFCND > MDL Abo update (@@ABO/@@ABOABA) More...

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 SEU SEU 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 menu 2. Select option ‘2’ from the Work with members display in PDM to browse through the source members 3. Select option ‘5’ from the Work with members display in PDM to edit source members 4. 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.

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. 20 of 148

Functions of DFU DFU 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 148

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 Categories
The 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’. Contains objects required to run software developed on the System/38. The software would then be executed in ‘System/38 mode’ Contains IBM supplied objects for general use. This library is present in every library list unless explicitly removed. 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. Service engineer library. Reclaim storage library .It is created when a Reclaim Storage command(RCLSTG) is executed and would contain objects that were purged by the command. Report Program Generator library. It contains RPG compiler and the objects required to enter,edit and compile RPG programs.

3.

QSYS38

4. 5.

QGPL QTEMP

6. 7.

QSRV QRCL

8.

QRPG

22 of 148

9.

QCBL

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

10. QIBU 11. QINS

Interactive data base utilities library. 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: DSPLIBL Display library list 23 of 148

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

Additional Recommended Reading Material 1. 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

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

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 • 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: 25 of 148

• •

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 200 View of a Physical File: File Level Record Level Field Level Key-Field Level Unique R Recfmt Name Age Phone Name 20 10 P 10 P 3

k

26 of 148

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 endusers’ needs • A logical file can contain up to 32 record formats and can obtain data from 2 to 32 physical files Components 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 : • Record Level : • Join Level : • Field Level Check(AB, • • Unique, LIFO, FIFO, Jdftval(JLF) Jfile (Join File), Pfile (Physical file), Text Jdupseq, JFld, Join : Alias, Reffld, Edtcde, Datfmt, Datsep, ME, MF), Cmp/Comp, ColHdg, Dft, Range, Timfmt, Timsep, Values, JRef Key-field Level : Absval, Descend, Signed, Unsigned Select/Omit Level : Comp, Range, Values, All R PFRecfmt1 K Cust# PFILE(PF1)

View of a Logical File: Record Level Key-field Level

27 of 148

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 J Enum Ename Dept K Enum S Enum 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 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 28 of 148 JFILE(PF1 PF2) JOIN( 1 2 ) JFLD( ENO ENUM ) JREF(1) JREF(1) JREF(2) comp GT 1010

• 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 Field level Cust# Key-field Level K Cust# Record Level R PFRecfmt2 Field level Cust# Key-field Level K Cust#

PFILE(PF1) PFILE(PF2)

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 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. 2. SC41-9659-02 SC41-9658-02 AS/400 Database Guide AS/400 Data Management Guide

29 of 148

30 of 148

Chapter IV: Data Description Specification (DDS)
Data Description Specifications(DDS) defines all attributes of a file and which are coded in 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 Application Development 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 Files
The Data Description Specifications(DDS) for Physical Files are defined in data specifications in the following layout: Positions Name Entry Explanation 1-5 6 7 8-16 17 19-28 29 Sequence number Form type Comment Reserved None ‘A’ ‘*’ Blank This is an optional column and may be used to identify, mark or tag source statements. Denotes ‘A’ Specification Denotes a comment line. Comments may be entered betweenpositions 8 and 80. This position Is not used for physical files and must be blank. Record format name. Field name. key field name. Record name or field name or key field name. Denotes that a definition and attributes of the named field are to be referenced from a previously defined field.

Type of Name ‘R’ ‘‘ ‘K’ Name Reference R

31 of 148

Positions 30-34

Name Length

Entry

Explanation Length of the field. The following are the valid lengths for various types of fields. Character 1 to 32766 Hexadecimal 1 to 32766 Binary 1 to 9 Numeric 1 to 31 Packed decimal Zoned decimal Binary Floating point Character Hexadecimal Date Time Timestamp. Number of decimal positions Both input and output Defaults to B This column is reserved and is not used by physical files.

35

Data Type

P S B F A H L T Z ‘B’ ‘‘

36-37 38 39-44 45-80

Decimal position Usage Location 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. Naming Conventions 32 of 148

The 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 Keywords Record level Keywords Field level Keywords Key-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 Out When 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 Out When 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 Out When 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 Reference Used to indicate the name of another file from which field references wherever indicated are to be retrieved.  UNIQUE Unique Key Used to indicate that records with duplicate key values will not be allowed in this file. Record Level Keywords  TEXT Text Used to assign descriptive text for the record format. Field Level Keywords  ALIAS Alias Name Used to indicate the alias name for the named field.  ALWNULL Allow Null value Used to indicate that the field may be written with NULL value (blanks for character fields and zeroes for numeric fields) 33 of 148

 CHECK Check values Used to provide certain validity rules for the named field.The values associated with this keyword are as follows: AB Allow blanks ME Mandatory Entry MF Mandatory Full M10 Modulus 10 validation M10F Modulus 10 validation(IBM variation) M11 Modulus 11 validation M11F 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 Heading Used 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 Format Used 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 separator Used to identify the character used to separate the elements of a date.  DFT Default Value Used to nominate a default value when the record is written.  EDTCDE Edit Code Used to identify a system-supplied editing rule for the named field. Rules could include zero suppression, zero balance, sign etc.  RANGE Range Used to specify a range of values that are allowed to be input in to the named field.  REFFLD Referenced Field Used 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 Used to define the format in which time is to be stored in the named field.  TIMSEP Time Separator 34 of 148

Used to identify the character to be used to separate the elements namely hour,minute and second of time.  VALUES Values Used 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 Value Used 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 Sequence Used 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 Signed Used 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 148

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

Positions 1-5 6 7 8-16 17

Name Sequence Number Form Type Comment Conditioning

Entry None ‘A’ ‘*’ Blank

Type of Name ‘R’ J ‘‘ ‘K’ ‘S’ ‘O’ Reserved Name Reference Length R Blank

Explanation This is an optional column and may be used to identify mark or tag source statements. Denotes ‘A’ specification Denotes a comment line .Comments may be entered between positions 8 and 80. This position is not used for logical files and must be blank Record format name Join Specification Field name Key field Name Select Criteria Omit Criteria This position is not used for logical files and must be blank Record name or field name or key field name Denotes that a definition and attributes of the named filed are to be referenced from a previously defined field. Length of the field the following are the valid lengths for various types of fields. Character 1 to 32766 Hexadecimal 1 to 32776 Binary 1 to 9 Numeric 1 to 31 Packed decimal Zoned decimal Binary Floating point Character Hexadecimal Date Time 36 of 148

18 19-28 29 30-34

35

Data Types

P S B F A H L

Positions

Name T Z

Entry

Explanation Timestamp Number of decimal positions.

36-37 38 39-44 45-80

Decimal Position Usage Location Keywords

‘B’ Blank

Both input and output Default to B Thos column is reserved and is not used by logical files.

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 Select Used 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 out When 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 Out When 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 Out When 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 Key Use to indicate that records with duplicate key value will not allowed in this file.

37 of 148

Record Level Keywords  PFILE Physical File Used 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 Text Used to assign descriptive text for the record format. Field Level Keywords  ALIAS Alias Name Used to indicate the alias name for the named field .  CHECK Check Values Used to provide certain validity for the named field. The value associated with this keyword are as follows: AB Allow Blanks ME Mandatory Entry MF Mandatory Full M10 Modulus 10 Validation M10F Modulus 10 Validation(IBM variation) M11 Modulus 11 Validation M11F Modulus 11 Validation(IBM variation) Example,CHECK (ME).  CMP/COMP Compare Value Used to provide validation to specify that named field must contain value specified in this parameter.Example,COMP(*EQ’A’)  COHDG Column Heading Used 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 Format Used 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 Separator Used to identify the character used to separate the elements of a date.  EDTCDE Edit Code Used to identify a system-supplied editing rule for the named field.Rules could include zero suppression,zero balance ,sign,etc.  TEXT Text Used 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 Format 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. 38 of 148

 VALUES Values Used 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 Value Used 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 Sequence Used 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 Signed Used 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 userdefined 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 148

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 Field Used 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 Join Identifies 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 148

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

Legend:

41 of 148

(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 00050A (2) R CUSMST 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 0 00130A (4) CRDLMT 8 2 00140A (5) K ACTNUM

(1) REF(MLGREFP) TEXT('Customer Master Record')

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 148

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 FILE 00030A 00040A R CUSMST1 00050A ACTNUM 00060A NAME 00070A STATE 00080A LASTNAME 00090A (2) K ACTNUM 00100A* 00110A R CUSMST2 00120A ACTNUM 00130A NAME 00140A ZIP 00150A K *NONE 00160A (2) K NAME

(1)PFILE(CUSMSTP)

I

(3)SST(NAME 8 10) (1)PFILE(CUSMSTP)

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
00010A*

43 of 148

00020A* SAMPLE LOGICAL FILE (CUSMSTL2) 00030A* 00040A 00050A R CUSREC 00060A 00070A ACTNUM (3) 00080A NAME (3) 00090A ADDR (3) 00100A (4)K ACTNUM

(1)UNIQUE (2)PFILE(CUSMSTP) TEXT('Logical File Master Record')

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 00020A 00030A 00040A 00050A 00060A 00070A 00080A 00090A A (1)R JOINREC J (3) J (4) (4) (4) (4) NAME ADDR PHONE SALARY (2) JFILE(PF1 PF2 PF3) JOIN(PF1 PF2) JFLD(NAME NAME) JOIN(PF2 PF3) JFLD(NAME NAME) (5) JREF(1)

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. (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, 44 of 148

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 Files
The 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 Material 1. SC41-9659-02 AS/400 : Database Guide 2. SC41-9620-02 AS/400:DDS Reference

45 of 148

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 148

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=Prompt Shows Work with Fields display.  F6=Condition Shows the Condition Work Screen display.  F9=Select additional records Selects additional records to display on the Design image work screen.  F10=Database Shows the display for selecting Database Files display.  F11=Non-display selected fields Toggle between two fields lists that are displayed on the bottom row of the work screen.  F12=Cancel Save 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=Ruler Place 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=Print Print the current contents of the Design Image work screen.  F18=Tab Moves the cursor to the attribute position of the next field.  F19=Back Tab Moves the cursor to the attribute position of the previous field.  F20=Reverse Image Constants Switch the reverse imaging of constants on and off.This reverse imaging is temporary and does not affect the compiled image.

47 of 148

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 constant 1. 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 148

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 148

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 Key Used to assign an alternate command key as the help key.  ALTPAGEDOWN Alternate Page Down Key Used to assign an alternate command key as the page down key

50 of 148

 ALTPAGEUP Alternate Page Up Key Used to assign an alternate command key as the page up key  ALWGPH Allow Graphics Used 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 Keys Used to assign the usage of indicators to be associated with command keys.  CFnn Common Function Keys Used 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 default Defined at the file level so that the field level defaults can be overridden with the user specified attributes.  DSPSIZ Display size Used to assign the display size of the work station display.  HELP Help key Used to assign an indicator for the Help key so that the program may recognize its usage.  HOME Home key Used to assign an indicator for the Home key so that the program may recognize its usage.  MSGLOC Message Location Used to identify a line of display where the messages may be displayed.  PRINT Print key Used 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 File Used to identify a file from which all the field references are to be derived from.  ROLLUP Rollup Key Used 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 148

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 Alarm Used to specify that the work station alarm is to be sounded when the named record format is output  ALWGPH Allow Graphics Used 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 Assume Used 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 this Keyword overlay the named record format over the previous display  BLINK Blink Used to indicate that named record format is to blink when displayed.  CHANGE Change Used 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 default Defined at the record level so that field level defaults can be overridden with the user specified attributes.  CSRLOC Cursor Location Used to position the cursor in a specified row-column position when the screen is displayed.  ERASE Erase This keyword is used to erase a record in a specified row-column position when the screen is displayed.  ERASEINP Erase Input Used to erase input fields from the named record format before the next output operation on the display file. ERRMSG Error Message

52 of 148

Used to specify the text to be displayed as an error message upon occurrence of an error condition.  ERRMSGID Error Message Id Used to identify a message identity from a named message file to be displayed as a error Message upon the occurrence of an error condition  HLPCMDKEY Help Command Key Used to specify an indicator to be associated with the Help Key for the named record format.  HOME Home Key Used to assign an indicator for the Home key so that the program may recognize its usage.  KEEP Keep Display Used 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 Overlay Used to retain the display of the format already displayed when the named record format is to be displayed.  PRINT Print Key Used to identify a printer file name into which any screen prints are to be directed  PROTECT Protect Used to identify that all the input capable fields in the named format are to be input inhibited.  PUTOVER Put over Used 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 Alias Used 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 148

 CHGINPDF Change input default Defined at the field level so that field defaults can be overridden with the user specified attributes.  CHECK Check Used 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 Compare Used to specify a literal value against which any input value to the field is validated on an input operation  COLOR Color Used to assign a color to a field or constant when it is displayed. Attribute values are GRN WHT RED TRQ YLW PNK BLU Green White Red Turquoise Yellows Pink Blue

 DATE Date Used to specify that the system date is to be displayed in the specified position  DFT, DFTVAL Default value Used to assign a default value to a field to be displayed during an output operation  DLTCHK Delete validity checking Used to specify that any validity checking specified in the definition of the referenced field is to be ignored for the named field  DLTEDT Delete Editing Used to specify that any editing rules specified in the definition of the referenced field is to be ignored for the named field.  DSPATR Display attribute Used to nominate a display attribute to be attached to the named field during an output operation. Valid values are BL Blink 54 of 148

CS HI ND PC PR RI UL

Column separators High-light Non – display Position Cursor Protect Reverse Image Underline

 EDTCDE Edit code Used 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 word Used to specify the user defined editing rules for both alphabetic and numeric fields.  OVRATR Override attributes Used 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 Range Used to specify a range of values that are valid input values for the named variable  REFFLD Referenced field name Used to specify the name of a previously defined field from the file indicated as the referenced file at the file level.  SYSNAME System name Used to indicate that the system name is to be displayed in the specific row-column position at the next output operation  TEXT Text Used to attach descriptive text for the named variable to be used when viewing or printing the display file field definitions.  TIME Time Used to indicate that the system is to be displayed in the specific row-column position upon the next operation to the screen  USER User name Used 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 148

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

56 of 148

Chapter VI: RPG/400

RPG/400 Language Concepts
RPG 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 148

1. 2. 3. 4. 5. 6. 7.

RPG/400 allows for the use of externally described files. RPG/400 supports character string operations. RPG/400 supports sub file initialization for data structure elements. RPG/400 allows indentation of IF-ELSE and DO statements in source. RPG/400 allows the use of figurative named constants. RPG/400 supports exception and error handling. 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 F E L I C O Control Specification File Specification Extension Specification Line counter Specification Input Specification Calculation Specification Output Specification

Details of the seven RPG specifications are as follows:

58 of 148

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 opcode Classification are :  Arithmetic Operations  Move Operations 59 of 148

                

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 ADD Factor 2 Result Field Indicators HI LO EQ + - Z

Addend

Addend

Sum

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

Z-ADD (Zeroise and add)
Factor 1 Code Z-ADD Factor 2 Result Field Indicators HI LO EQ + - Z

Addend

Addend

Sum

Initialize a variable to zeros and add a second variable to the first Example: 60 of 148

Z-ADD Z-ADD Z-ADD SUB (Subtract statement)
Factor 1 Code Factor 2

FIELDA 1 *ZEROS

FIELDB FIELDA FIELDA

Result Field

Minuend

SUB

Subtrahend

Difference

Indicators HI LO EQ + - Z

Subtract the value of one variable from a third variable Example FIELDA 10 SUB SUB SUB SUB FIELDB FIELDA 10 3 FIELDC FILEDB FIELDB FIELDA

Z-SUB (Zeroise and subtract)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ + - Z

Minuend

Z-SUB

Subtrahend

Difference

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 FIELDA This 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 + - Z

Multiplica nd

MULT

Multiplier

Product

Example FIELDA 5 FIELDA

MULT MULT MULT

FIELDB FIELDA 5 61 of 148

FIELDC FIELDB FIELDB

3

MULT MULT MULT

5 FIELDA *ZEROS

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

Dividend

DIV

Divisor

Quotient

Indicators HI LO EQ + - Z

Example: FIELDA 5 FIELDA 5

DIV DIV DIV DIV

FIELDB FIELDA 5 3

FIELDC FIELDB FIELDB 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 + - Z

MVR

Remainder

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 Move Operations: MOVE (Move)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

FIELDA

FIELDB

MOVE

Source

Target Field

+ - ZB

62 of 148

field

Moves the contents of a variable or constant into a second variable. This operation is rightjustified. 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 leftjustified .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, xx can be: xx GT LT EQ Meaning Factor 1 is greater than factor 2. Factor 1 is less than factor 2. Factor 1 is equal to factor 2. 63 of 148

NE GE LE Blanks

Factor 1 is not equal to factor 2. Factor 1 is greater than or equal to factor 2. Factor 1 is less than or equal to factor 2. 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 *IN25 CABxx ‘1’ TAG01  CASxx (Compare and execute subroutine)
Code Factor 2 Result Field Indicators HI LO EQ

Factor 1

Comparand

CASxx

Comparand

Subroutine

HI LO EQ

64 of 148

Name

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 ‘ABCDE’ FIELDC 10 FIELDD *IN25 CASxx CASxx CASxx CASxx CASxx CASxx CAS FIELDB FIELDC ‘ABCDE’ FIELDD 10 ‘1’ SUB01 SUB01 SUB01 SUB01 SUB01 SUB01 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 operation Example: 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 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 65 of 148

‘ABCDE’ FIELDC 10 FIELDD *IN25 WHxx (When)
Factor 1 Code

DOWxx DOWxx DOWxx DOWxx DOWxx

FIELDC ‘ABCDE’ FIELDD 10 ‘1’

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. FIELDA ‘ABCDE’ FIELDC 1 FIELDD 2 COMP COMP COMP COMP COMP COMP FIELDB FIELDC ‘ABCDE’ FIELDD 1 5 66 of 148

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

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 KFLD KFLD FILEDA FILEDB FILEDC 67 of 148

DEFN (Definition)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

*LIKE *NAMVAR

DEFN DEFN

Referenced field External data area

Defined field 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 *NAMVAR DEFN DEFN FIELDA FMINDT FIELDB AREA01

TAG(Tag) A tag statement is used to identify the address of a branching operation such as CABxx or GOTO. TAG01 Initialization Operations CLEAR (Clear)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

TAG

*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. 68 of 148

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 Source string 1 Code CAT (p) Factor 2 Source string 2: number of Blanks Result Field Target string Indicators HI LO EQ

The CAT operation concatenates the character string specified in factor 2 to the end of the character string specified in factor 1 and places it in the result field. If no factor 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 Name the value of the result field after this statement is executed is: 'bMIKEbbbSMITHb'

69 of 148

CHECK (Check Characters)
Factor 1 Comparator string Code CHECK Factor 2 Base string:start Result Field Left-position Indicators HI LO EQ _ ER FD

The CHECK operation verifies that each character in the base string (factor 2) is among 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 the end of the base string is encountered. If no incorrect characters are found, the result 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 position C\ 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 letters I\ 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 6 C LETTER CHECKFIELD ARRAY 90 C\ C\ In the following example, because FIELD contains only the C\ letters A to J, ARRAY=(000000). Indicator 90 turns off. C\ C MOVE 'FGFGFG' FIELD 6 C LETTER CHECKFIELD ARRAY 90

CHEKR (Check Reverse)
Factor 1 Code Factor 2 Result Field Indicators

70 of 148

Comparat or string

CHEKR

Base string:start

Right-position

HI LO EQ _ ER FD

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

SCAN (Scan Character String)
Factor 1 Comparator string:Length Code SCAN Factor 2 Base string:start Result Field Left Most Position Indicators HI LO EQ _ ER FD

The SCAN operation scans a character string (base string) contained in factor 2 for a substring (compare string) contained in factor 1. The scan begins at a specified location contained in factor 2 and continues for the length of the compare string which 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 in C\ position 3 in factor 2; 3 is placed in the result field. C\ Indicator 90 is set on because the string is found. Because C\ no starting position is specified, the default of 1 is used. C 'ABC' SCAN 'XCABCD' RESULT 90

XLATE (Translate)
Factor 1 From:To Code XLATE Factor 2 String:start Result Field Target String Indicators HI LO EQ __ ER __

Characters in the source string (factor 2) are translated according to the From and To 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 in the To string. XLATE starts translating the source at the location specified in factor 2 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 result C\ in RESULT will be '999-9999'. C\ C MOVE '999.9999'NUMBER 8

71 of 148

C ' ':'-' 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 to I\ uppercase. As a result, RESULT='RPG DEP'. I\ I 'ABCDEFGHIJKLMNOPQRSC UP I 'TUVWXYZ' I 'abcdefghijklmnopqrsC LO I 'tuvwxyz' C\ CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++ C MOVE ‘RpG Dep' STRING 7 C LO:UP XLATESTRING RESULT 90 C\ C\ In the following example all values in the string are translated C\ to lowercase. As a result, RESULT='rpg dep'. C\ C MOVE 'RpG Dep' STRING 7 C UP:LO XLATE STRING RESULT 90

SUBST (Substring)
Factor 1 Length to extract Code SUBST Factor 2 Base string:start Result Field Target string Indicators HI LO EQ __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 the result 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 starting C\ at position 3 for a length of 2. The value 'CD' is placed in the C\ result field RESULT. Indicator 90 is not set on because no error C\ occurred. C Z-ADD 3 T 20 C MOVEL'ABCDEF' STRING 10 C 2 SUBSTSTRING:T RESULT 90

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 Than 72 of 148

LE EQ NE GT GE

Less than or Equal to Equal to Not Equal to Greater Than 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 Subroutine Code Factor 2 Result Field Indicators HI LO EQ

BEGSR

name

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

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. TAG99 ENDSR ENDSR

73 of 148

Indicator Operations SETON (Set on indicator)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ
ON ON ON

SETON

Sets on indicator to value ‘1’. SETON SETON SETON SETON SETON SETOF (Set off indicator)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ
ON ON ON

25 25 25

26 25

27 27 27 27

SETOF

Sets on indicator to value ‘0’. SETOF SETOF SETOF SETOF SETOF 25 25 25

26 25

27 27 27 27

Structured Programming Operations 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. 74 of 148

Example: FIELDA ‘ABCDE’ FIELDC 10 FIELDD *IN25 ANDxx (And condition)
Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

ORxx ORxx ORxx ORxx ORxx ORxx

FIELDB FIELDC ‘ABCDE’ FIELDD 10 ‘1’

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 FIELDC FIELDC ANDxx ‘ABCDE’ 10 ANDxx FIELDD FIELDD 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. 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

75 of 148

DO IF SL DO (Do Iteration)
Factor 1 Code

DO DOUxx DOWxx IFxx SELEC

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* C* C* C* C* C* C* C C C C C The DO group can be processed 10 times. The DO group stops running when the index value in field X is greater than the limit value (20) in factor 2 . The starting value of 2 is specified in factor 1 of the DO operation, and the incrementing value of 2 is specified in factor 2 of the ENDDO operation. 2 DO 20 : : : ENDDO 2 X 30 DO 10 TIMES

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 statement o Zero or more WHxx groups o An optional OTHER group 76 of 148

o

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 148

File Operations File Specification Combinations:
Spec Record Device Record User Address Addition Control Type Input Mode: Opcodes can be performed : READ, READE, REDPE, READP, SETLL, SETGT, CHAIN, (OPEN, CLOSE) F I F E K DISK (UC) File Name File Type File Designation File Format

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 F U O F E K K DISK A A (UC) (UC) Output Mode: WRITE, (OPEN, CLOSE)

OPEN (Open File for Processing)
Factor 1 Code OPEN Factor 2 File Name Result Field Indicators HI LO EQ __ 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 CLOSE Factor 2 File Name Result Field Indicators HI LO EQ __ 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 UC FFILEX I E DISK \...1....+....2....+....3....+....4....+....5....+....6....+....7... CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++

78 of 148

C\ C\ C 97N98 C 97N98N99 C\ C\ C

OPEN EXCPTN WRITEERREC CLOSEFILEX

99 99=NO SUCCESS

SETLL (Set Lower Limits)
Factor 1 Search argument/*HIVAL/ *LOVAL Code SETLL Factor 2 File Name Result Field Indicators HI LO EQ NR ER EQ

The SETLL operation positions a file at the next record that has a key or relative record number that is greater than or equal to the search argument (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 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 order number (ORDER) field. There are multiple records for each order. ORDFIL looks like this in the calculation specifications:
N010N02No3 N55 Factor 1 ORDER Code SETLL GOTO Factor 2 ORDFIL NOTFND Result Field Indicators HI LO EQ 55

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 is not processed. 79 of 148

SETGT (Set Greater Than)
Factor 1 Search argument/*HIVAL/ *LOVAL Code SETGT Factor 2 File Name Result Field Indicators HI LO EQ NR ER __

The SETGT operation positions a file at the next record with a key or relative record number 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 file description specifications). In this example, the file ORDFIL contains order records. The key field is the order number (ORDER) field. There are multiple records for each order. ORDFIL looks like this in the calculation specifications:
N010N02No3 Factor 1 ORDER Code SETGT READ Factor 2 ORDFIL ORDFIL Result Field Indicators HI LO EQ 80

READ (Read a Record)
Factor 1 Code READ Factor 2 File Name/Record Name Result Field Data structure Indicators HI LO EQ __EREOF

The READ operation reads the record, currently pointed to, from a full procedural file
Example:
N010N02No3 Factor 1 *LOVAL *IN80 Code SETLL READ DOWEQ . . . READ ENDDO Factor 2 ORDFIL ORDFIL ‘0’ Result Field Indicators HI LO EQ 80

ORDFIL

80

READE (Read Equal Key)
Factor 1 Search argument Code READE Factor 2 File Name/Record Name Result Field Data structure Indicators HI LO EQ __EREOF

80 of 148

The READE operation retrieves the next sequential record from a full procedural file if the key of the record matches the search argument. Example:
N010N02No3 Factor 1 *LOVAL ORDER *IN80 Code SETLL READE DOWEQ . . . READE ENDDO Factor 2 ORDFIL ORDFIL ‘0’ Result Field Indicators HI LO EQ 80

ORDER

ORDFIL

80

READP(Read a Previous Record)
Factor 1 Code READP Factor 2 File Name/Record Name Result Field Data structure Indicators HI LO EQ __ERBOF

The READP operation reads the prior record from a full procedural file Example:
N010N02No3 Factor 1 *HIVAL *IN80 Code SETGT READP DOWEQ . . . READP ENDDO Factor 2 ORDFIL ORDFIL ‘0’ Result Field Indicators HI LO EQ 80

ORDFIL

80

REDPE (Read Prior Equal)
Code REDPE Factor 2 File Name/Record Name Result Field Data structure Search argument Indicators HI LO EQ __ERBOF

Factor 1

The REDPE operation retrieves the next prior sequential record from a full procedural file if the key of the record matches the search argument. If the key of the record does not match the search argument, Example:
N010N02No3 Factor 1 Code Factor 2 Result Field Indicators HI LO EQ

81 of 148

*HIVAL ORDER *IN80

ORDER

SETGT REDPE DOWEQ . . . REDPE ENDDO

ORDFIL ORDFIL ‘0’

80

ORDFIL

80

CHAIN (Random Retrieval from a File)
Factor 1 Search argument Code CHAIN Factor 2 File Name Result Field Data structure Indicators HI LO EQ NRER __

The CHAIN operation retrieves a record from a full procedural file
Example:
N010N02No3 Factor 1 ORDER *IN80 Code CHAIN IFEQ Factor 2 ORDFIL ‘1’ Result Field Indicators HI LO EQ 90

WRITE (Create New Records)
Factor 1 Code WRITE Factor 2 File Name Result Field Data structure Indicators HI LO EQ __ER __

The WRITE operation writes a new record to a file. Example:
N010N02No3 Factor 1 Code WRITE Factor 2 ORDFIL Result Field Indicators HI LO EQ 91

UPDAT (Modify Existing Record)
Factor 1 Code UPDAT Factor 2 File Name Result Field Data structure Indicators HI LO EQ __ER __

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.

82 of 148

• •

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.
Factor 1 ORDER *IN80 Code CHAIN IFEQ . . . UPDAT Factor 2 ORDFIL ‘0’ Result Field Indicators HI LO EQ 90

Example:
N010N02No3

ORDFIL

89

DELET (Delete Record)
Factor 1 Search Arguement Code DELET Factor 2 File Name Result Field Indicators HI LO EQ __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 DELET Factor 2 ORDFIL Result Field Indicators HI LO EQ 89

Calling Operations CALL (Call a Program)
Factor 1 Code CALL Factor 2 Program name Result Field Plist name Indicators HI LO EQ __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 be called.

83 of 148

PARM (Identify Parameters)
Factor 1 Target field Code PARM Factor 2 Source field Result Field Parameter Indicators HI LO EQ

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 to the called program. When a data structure with multiple occurrences is passed to the called program, all occurrences of the data structure are passed as a single field. However, if a subfield of a multiple occurrence data structure is specified in the result field, only the current occurrence of the subfield is passed to the called program. 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, the calling and called parameters do not have to use the same field names for fields that are passed. The attributes of the corresponding parameter fields in the calling and called programs should be the same. If they are not, undesirable results 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. 84 of 148

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 PLIST name Code PLIST Factor 2 Result Field Indicators HI LO EQ

Factor 1 must contain the name of the parameter list. If the parameter list is the entry 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 an operation 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 and C\ allows PROG2 to access the data in the parameter list fields. C CALL 'PROG2' PLIST1 C\ C\ In the second PARM statement, when CALL is processed, the C\ contents of factor 2, *IN27, are placed in the result field, C\ BYTE. When PROG2 returns control, the contents of the result C\ field, BYTE, are placed in the factor 1 field, *IN30. Note C\ that factor 1 and factor 2 entries on a PARM are optional. C\ C PLIST1 PLIST C PARM AMT 52 C *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 a C\ CALL operation instead of a PLIST operation. C PARM AMT 52 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 the C\ PLIST statement identifies it as the entry parameter list. C\ When control transfers to PROG2, the contents of the result C\ fields (FLDC and FLDG) of the parameter list are placed in C\ the factor 1 fields (FLDA and FLDD). When the called program C\ returns, the contents of the factor 2 fields of the parameter C\ list (FLDB and FLDE) are placed in the result fields (FLDC C\ and FLDG). All of the fields are defined elsewhere in the C\ program. C *ENTRY PLIST C FLDA PARM FLDB FLDC C FLDD PARM FLDE FLDG

85 of 148

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

(Move array)
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: ° 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: 86 of 148

MOVEA FIELDA MOVEA ‘ABCDE’ MOVEA 25 MOVEA FIELDA MOVEA ‘ABCDE’ MOVEA 25 MOVEA FIELDA MOVEA ‘ABCDE’ MOVEA 25 MOVEA ARRA MOVEA ARRA,X MOVEA ARRA,3 MOVEA ‘1111’ MOVEA ‘0000’ MOVEA ‘1010’ MOVEA *ALL’0’ XFOOT (Array Total)
Factor 1 Code Factor 2 Result Field

ARRA ARRA ARRA ARRA,X ARRA,X ARRA,X ARRA,3 ARRA,3 ARRA,3 FIELDA FIELDB FIELDC *IN,25 *IN,25 *IN,25 *IN,25

Indicators HI LO EQ

XFOOT

Array name

Sum

+

- Z

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

LOKUP (Lookup) Search for a character, named variable or a literal from a specified position in an array FIELDA LOKUP ‘ABCDE’ LOKUP 25 LOKUP FIELDA LOKUP ‘ABCDE’ LOKUP 25 LOKUP 87 of 148 ARRA ARRA ARRA ARRA,3 ARRA,3 ARRA,3

FIELDA LOKUP ARRA,X ‘ABCDE’ LOKUP ARRA,X 25 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 specification Example: SORTA 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 ROLBK (Roll Back) Undelete all database changes since the previous commit or rollback operation ARRA

RPG/400 Indicator
Indicators 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, OV 01 to 99 88 of 148

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 99 H1 to H9 L1 to L9 LR U1 to U8 RT 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 DISK F\ Entries for Physical file definition: File name (col 7 -14) – Name of the Physical file File Type (column 15)- letter I defines U,O,C and D the physical file as an input file .Other types are

File Designation (column 16)- Letter F defines the file is fully procedural file File Format(column 19)- Letter E denotes the defined File is externally defined. F denotes program

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 DISK F\ Entries for Physical file definition: File name (col 7 -14) – Name of the Physical file

89 of 148

File Type (column 15)- letter I defines U,O,C and D

the physical file as an input file .Other types are

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 sequence. the file will be processed in arrival

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 PARTNO I 11 160QTY I 17 20 TYPE I 21 21 CODE I 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 Guide 2 SC09-189-2 RPG/400 Reference Manual 3 SC09-1349-01 SAA AD/Cycle RPG/400 Reference Manual

90 of 148

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 Subfile
Subfile 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} 91 of 148

• SFLPAG • SFLSIZ • Subfile Keywords

{ Subfile Page} {Subfile Size }

The following keywords are defined in the subfile control record format and are attributed to all the record for the subfile.  SFL Subfile Record Format Identifies the named record format as a subfile record format  SLFCLR Subfile clear Used 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 format Identifies the named record format as the subfile control record format  SFLDLT Delete subfile Used 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 drop Used 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 subfile Used to indicate that when the associated indicator is set on, the subfile is to be displayed upon the next output operation.  SFLDSPCTL Display subfile control Used to indicate that the associated indicator is set on, the subfile record format is to be displayed upon the next output operation.  SFLEND Subfile end Used 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 subfile Used 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 line Used to specify the number of subfile records that should be displayed in the line of display  SFLMSG Subfile message Used to associate an error message with an error condition at the subfile control record level  SFLPAG Subfile page Used to specify the number of subfile records to be displayed in one page of display  SFLRCDNBR Subfile record number

92 of 148

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 active Used 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 value Used to specify the number of records that are to be paged up/down when the Roll Up/Roll Down keys are used  SFLSIZ Subfile size Used 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 format Identifies the named record format as a subfile record format  SFLNXTCHG Subfile next changed record Associate 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 ******************* **********************

93 of 148

Handling Subfiles in RPG Programs
File 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 word RRNBR KSFILE SUBFIL In 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

94 of 148

Multi page subfiles:
There are three options for managing a multipage subfile: 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 Code Issues Option 1. Load all subfile • Simplest code • Limit of 9999 records

User Issues • 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. • 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. • 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.

2.Expanding subfile

• Code is more complex. • Limit of 9999 records.

3. Single Page Subfile

• Most complicated Code . • Use least memory. • No Size limit.

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. 95 of 148

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. SUBFILE PAGE < SUBFILE SIZE OR SUBFILE SIZE = SUBFILE PAGE + 1.
Physical file Test: A A A A A A A R TSTREC CODE NAME AGE PHONE K CODE UNIQUE 3 20 2P 0 10P 0

A*************** A Subfile for Load All: A*************** A R DSFRCD A*%%TS SD 20040203 031411 A CODE R A NAME R A AGE R A PHONE R A R DSFCTL A*%%TS SD 20040203 034504 A A A A A A 90 A 91 A 93 A 94 A A A A A A A A A A A A A

SFL RTAMIL REL-V5R1M0 5722-WDS O 5 4REFFLD(TSTREC/CODE RTAMIL/TEST) O 5 12REFFLD(TSTREC/NAME RTAMIL/TEST) O 5 33REFFLD(TSTREC/AGE RTAMIL/TEST) O 5 48REFFLD(TSTREC/PHONE RTAMIL/TEST) SFLCTL(DSFRCD) RTAMIL REL-V5R1M0 5722-WDS SFLSIZ(0015) SFLPAG(0014) CF03(03) CF05(05) OVERLAY SFLDSP SFLDSPCTL SFLCLR SFLEND(*MORE) 1 29'Load All Subfile Example' DSPATR(UL) 2 30'For Demo Purpose Only' DSPATR(BL) DSPATR(UL) 4 4'Code' DSPATR(UL) 4 12'Name' DSPATR(UL) 4 33'Age' DSPATR(UL) 4 48'Phone' 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

96 of 148

F SFLRRNKSFILE DSFRCD C* C EXSR INZSR 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 *******************

97 of 148

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) A 4 33'Age'

98 of 148

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 C COUNT IFEQ 6 C LEAVE C ENDIF

99 of 148

C C C

READ TSTREC ENDDO ENDSR ************************************End of data

94

**********************

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' A DSPATR(UL) A 4 12'Name' A DSPATR(UL) A 4 33'Age' A DSPATR(UL) A 4 48'Phone'

100 of 148

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' C COUNT ANDLT6 C ADD 1 SFLRRN C ADD 1 COUNT C COUNT IFEQ 1 C MOVE CODE FCODE 3 C ENDIF C WRITEDSFRCD2

101 of 148

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) 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) 102 of 148

* 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

103 of 148

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 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. 104 of 148

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 array 2) Prerun time array 3) 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:

105 of 148

*...+... 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 * * 312831303130313130313031 Related 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

106 of 148

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.

107 of 148

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 Time arrays(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 record format that store the data for the Run Time array are entered beginning in column 21.

Array name, comma and element number are entered in the field name columns.

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:

108 of 148

*...+... 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 Arrays
The 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 for which 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 EDISK F\ E....FromfileTofile++Name++N/rN/tbLenPDSArrnamLenPDSComments E ARRFILE DPTNOS 1 50 5 0 DEPT NUMBERS E\ CLðNð1Nð2Nð3Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments+++++++ C\ The LOKUP operation is processed and, if an element of DPTNOS equal C\ to the search argument (DPTNUM) is found, indicator 2ð is set on. C DPTNUM LOKUPDPTNOS 2ð C\ C\ Otherwise, indicator 2ð is not set on and the GOTO statement C\ conditioned by N2ð causes a branch to the BADNUM TAG.

109 of 148

C C C C C

N20 GOTO BADNUM : : Calculations : 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 5 positions in length (5 in position 27). The E in position 39 indicates that the file is further 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 in length (position 42) with zero decimal positions (position 44). One department number can be contained in each record (1 in position 35). However, each record does not have to contain an entry. Any record that does not contain an entry is filled 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. This numeric 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 EDISK F\ E....FromfileTofile++Name++N/rN/tbLenPDSArrnamLenPDSComments+++++++++ E ARRFILE DPTNOS 1 5ð 5 ð DPTDSC 2ð DEPT NO/DESCRPTN E\ 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\ C\ C\ C\ C C\ C\ C C C At the end of a successful LOKUP, when an element has been found that contains an entry equal to the search argument DPTNUM, indicator 2ð is set on and the MOVE operation places the department description, corresponding to the department number, into DPTNAM. DPTNUM LOKUPDPTNOS,X 2ð If an element is not found that is equal to the search argument, the GOTO operation conditioned by N2ð causes a branch to BADNUM. N20 GOTO BADNUM MOVE DPTDSC,X DPTNAM 2ð 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 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. 110 of 148

Specifying an Array in Calculations
An entire array or individual elements in an array can be specified in calculation specifications. You can process individual elements like fields. Remember, if an array element is to be used as a result field, the array name with the comma and index 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 array name: • 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 the array name alone. These operations include but are not limited to: • BITON • BITOF • COMP • CABxx • TESTZ 111 of 148

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

112 of 148

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.

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 Blank Explanation Subfield is in zoned-decimal format or is character data,depending on the entry in position 52 of the subfield specifications.

113 of 148

P B

Subfield is in packed-decimal format. Subfield is in binary format. ____________
________________________________________________________

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 6 7-12 Entry I 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. Blank Blank: Program-described data structure. E: Externally described data structure. The data structure subfield definitions are retrieved from an externally described record format. 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. DS 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. Blank 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.

13-16 17

18

19-20 21-30

31-43 44-47

114 of 148

48-51 52-74

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

Examples:
Divide a field into subfields:
IDsname....NODsExt-file++.............OccrLen+......................* IPARTNO DS I..............Ext-field+............PFromTo++DField+...............* I 1 4 MFG I 5 10 DRUG I 11 13 STRNTH I 14 160COUNT I*

Using Data Structure to Group fields :
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..* IFilenameSqNORiPos1NCCPos2NCCPos3NCC................................* ITRANSACTNS 01 1 C1 2 C2 I....................................PFromTo++DField+L1M1FrPlMnZr...* I 3 10 PARTNO I 11 160QTY I 17 20 TYPE I 21 21 CODE I 22 25 LOCATN IDsname....NODsExt-file++.............OccrLen+......................* IPRTKEY DS I..............Ext-field+............PFromTo++DField+...............* I 1 4 LOCATN I 5 12 PARTNO I 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 YY IDsname....NODsExt-file++.............OccrLen+......................* I DS I..............Ext-field+............PFromTo++DField+...............* I 1 6 YYMMDD I 1 2 YY I 3 4 MM I 5 6 DD

115 of 148

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. When positions 44 through 47 do not contain an entry, the data structure is not a multipleoccurrence 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 multipleoccurrence 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 status data structure. information, or program-

*.. 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 |________________|

116 of 148

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 UDS I..............Ext-field+............PFromTo++DField+...............* I 1 6 PARTNBR I*

Explicitly retrieved and written: The Opcodes and reserved words related to the explicit processing of data are summarized as follows : OpCodes Function IN 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 program Reserved 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 : CL0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments++++++*

117 of 148

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

118 of 148

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 I I I I I DS *FILE FILE *OPCODE CODE *STATUS STATUS *RECORD RECORD *ROUTINE ROUTIN

. .

119 of 148

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

READAG

6

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 10position 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 I I I I SDS

*FILE *OPCODE *STATUS *RECORD

FILE CODE STATUS RECORD

120 of 148

I

. . . *PSSR STATUS BEGSR IFEQ 01011 MOVEL‘*GETIN’ EXCPT ERROUT ENDIF ENDSRREADAG

*ROUTINE ROUTIN

C C C C C C

READAG

6

121 of 148

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.

122 of 148

Some of the commonly used keywords are detailed below. File Level Keywords  REF Referenced File Used to specify a file that is to be referenced for all the subsequent referenced field definitions.  SKIPA Skip After Used 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 Before Used 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 Size Used to specify a character size to all variables and constants in the named record format.  CPI Characters per Inch Used 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 Drawer Used 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 multidrawer printer.  HIGHLIGHT Highlight Used to specify that all variables and constants of the named record format are to be highlighted while being printed.  LPI Line per Inch Used to specify the number of lines allowable per inch of stationery while printing the named record format. Record Level Keywords  PRTWLTY Print Quality Used to specify the print quality to be used while printing the named record format. SKIPA Skip After

123 of 148

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 Before 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 before printing the named record format.  SPACEA Space After Used 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 Before Used 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 Text Used to assign descriptive text to be associated with record format. Field Level Keywords  REFFLD Referenced Field Name Used to specify the name of previously defined field from the file indicator as the referenced file at the file level.  SKIPA Skip After Used 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 Before Used 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.)

124 of 148

 SPACEA Space After Used 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 Before Used 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 Text Used to assign descriptive text to be associated with record format.  TIME Time Used 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 Material 1. SC09-1416-02 RLU Users Guide and Reference.

125 of 148

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 Structure
A 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/ARA01 LEN 100 TYPE *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 are SBSD Subsystem name JOB Job name JOBD 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 where, ABC is taken by the system as being the subsystem name DEF as being the job name, and 126 of 148 ABC DEF XYZ

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 description DEV Device name RMTLOCNAME Remote location name JOBD Job description DFTUSR Default user MODE Mode MAXACT 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 name DEF is being the device name Delimiters Delimiters are special characters used to separate the various components of a CL statement. The following are valid CL delimiters. 127 of 148

‘:’

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 testlibrary’) 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

Concatenation
Variables 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 |> *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 |< 128 of 148

*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’ &FLDA *BCAT &FLDB &FLDB *TCAT ‘TEST01’ ‘ABCDTEST01 ‘ ‘ABCDE 1234 ‘ ‘1234TEST01’

Relational Expressions
The following are valid relational expressions allowed for use in CL programs. 1. 2. 3. 4. 5. 6. 7. 8. = > < >= <= -| -|> -|< *EQ *GT *LT *GE *LE *NE *NG *NL Equal to Greater than Less than Greater than or equal to Less than or equal to Not equal to Not greater than Not less than

Logical Expressions
The following are valid logical expressions allowed for use in CL programs. 1. 2. 3. & | -| *AND *OR *NOT And Or Not

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

129 of 148

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 program
All 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 DCL DCL VAR(&FLDA) VAR(&FLDB) VAR(&FLDC) LEN(10) LEN(6) LEN(9 2) TYPE(*CHAR) TYPE(*DEC) 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.

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 file 130 of 148

SNDF FILE(FILEB) Writes a record from the named file SNDRCVF 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 CHGVAR CHGVAR CHGVAR VAR(&FLDA) VAR(&FLDB) VAR(*INK25 ) VAR(&FLDC) VALUE(‘ABCDE’) VALUE(‘&FLDB + 1) VALUE(‘1’) 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)

An ELSE statement may optionally be used with an IF statement Additional Recommended Reading Material 131 of 148

1. 2.

SC21-8077-2 SC41-00300-02

Control Language: Programmer’s Guide-Vol I and II Control Language: Reference – 3 Volumes

132 of 148

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 the Program 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.

133 of 148

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): If doing selection against a character, date, time, or timestamp field, specify: OPNQRYF FILE(FILEA) QRYSLT('"' *CAT &CHAR *CAT '" *EQ FIELDA') 134 of 148

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 RTVSYSVAL OVRDBF VAR(&YEAR) TYPE(*CHAR) LEN(2) SYSVAL(QYEAR) RTNVAR(&YEAR) 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 CLOF DLTOVR PGM(ORDRPT2) OPNID(ORDMST) FILE(ORDMST) //Processing Program

ENDPGM

Additional Recommended Reading Material 1. DB2 UDB for AS/400 Database Programming 135 of 148

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 that message ID and substitute your own message. This doesn't mean you change the CPF9898 message in the actual message file. You simply 136 of 148

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

137 of 148

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 * * * * * A A 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. SFLMSGRCD(24) SFLMSGKEY SFLPGMQ

MSGKEY PGMQ

138 of 148

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

MSGCNS

* SEND MSG0003 FROM MESSAGE FILE XZY1337 TO PROGRAM MESSAGE QUEUE MOVEL 'MSG0003' MSGID MOVEL 'XZY1337' MSGF MOVE MSGCNS MSGDTA 62 MOVE 'I' MSGOPT EXSR SEND * * SEND MSG0001 FROM MESSAGE FILE XZY1337 TO PROGRAM MESSAGE QUEUE

C C C C *

MOVEL MOVEL MOVE EXSR

'MSG0001' 'XZY1337' 'I' SEND

MSGID MSGF MSGOPT

* SETON SFLEND INDICATOR FOR MESSAGE SUBFILE C SETON * WRITE MESSAGE SUBFILE C WRITE MSGSFLC 98

* WRITE/READ REGULAR SCREEN FORMAT C EXFMT FMT1

* CLEAR THE PROGRAM MESSAGE QUEUE C C * MOVE EXSR 'C' SEND MSGOPT

139 of 148

* WRITE MESSAGE SUBFILE C WRITE MSGSFLC

* WRITE/READ REGULAR SCREEN FORMAT C C EXFMT MOVE FMT1 '1' *INLR

**************************************************************** C *INZSR BEGSR

* MOVE THE PROGRAM NAME TO THE PROGRAM MESSAGE QUEUE FIELD C C C MOVEL MOVE ENDSR **************************************************************** * THIS SUBROUTINE CALLS A CL PROGRAM THAT SENDS THE MESSAGE * TO THE PROGRAM MESSAGE QUEUE. **************************************************************** C SEND BEGSR 'MSGSFLPG' 'M ' PGMQ PGMQ

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

PARM(&MSGID &MSGF &MSGDTA &MSGOPT) VAR(&MSGID) TYPE(*CHAR) LEN(7) VAR(&MSGF) TYPE(*CHAR) LEN(10) VAR(&MSGOPT) TYPE(*CHAR) LEN(1) VAR(&MSGDTA) TYPE(*CHAR) LEN(62) COND(&MSGOPT *EQ 'I') THEN(SNDPGMMSG + MSGID(&MSGID) MSGF(&MSGF) MSGDTA(&MSGDTA))

COND(&MSGOPT *EQ 'C') THEN(RMVMSG PGMQ(*PRV + (*)) CLEAR(*ALL)) *****************************End of Data*************************************

IF

USING APIs instead of a CL:
************************************************************************** * * Send message subroutine * c sndmsg begsr c c call parm 'QMHSNDPM' msgId

140 of 148

c c c c c c c c c

parm parm parm parm parm parm parm parm endsr

msgLoc msgRplDta msgRplDtaLen msgType msgQueue msgCallStack msgKey msgErr

*************************************************************** * Remove message subroutine *************************************************************** c rmvmsg begsr * c call 'QMHRMVPM' c parm msgQueue c parm msgCallStack c parm msgKey c parm msgRmv c parm msgErr **************************************************************************

141 of 148

Appendix A : RPG Opcodes Operation codes in RPG/400
Codes ACQ ADD(1/2) ANDxx BEGSR BITOF BITON CABxx CALL CASxx CAT (p) CHAIN(n) CHECK CHECKR(2) CLEAR CLOSE COMIT COMP(1) DEBUG DEFN DEFN DELET DIV (1/2) Factor 1 QRGRCOP P Addend Comparand Subroutine name Comparand Comparand Source String 1 Search argument Comparator String Comparator String *NOKEY Boundary Comparand Identifier *LIKE *NAMVA R Search Argument Dividend Factor 2 WORKSTN file Addend Comparand Bit numbers Bit numbers Comparand Program Name Comparand Source String 2:Number of Blanks File name Base String : start Base String : start Structure or Variable File Name Comparand Output file Referenced field Internal program area File name Divisor Result Field Sum Resulting Ind. ER + Z

Character field Character field Label PLIST name Subroutine Name Target String Data Structure Left most Position Right most Position

HI -HI

LO ER LO

EQ LR EQ

NR ---

ER ER ER

-FD FD

--HI Debug Information Defined field External data area NR Quotient +

ER ER LO

--EQ

ER -

-Z

142 of 148

DO DOUxx DOWxx DSPLY DUMP ELSE END ENDCS ENDDO ENDIF ENDSL ENDSR EXCPT

Starting Value Comparand Comparand Message identifier Identifier

Limit Value Comparand Comparand Output queue

Index Value

Response

--

ER

--

Increment Value Increment Value Label Return point EXCPT Name

Codes EXFMT EXSR FEOD FORCE FREE GOTO Ifxx IN ITER KFLD KLIST LEAVE LOKUP (1) (Array) LOKUP (1) (Table) MHHZO MHLZO MLHZO MLLZO

Factor 1

Comparand *LOCK

Factor 2 Result Field Record format name Subroutine name File name File name Program name Label Comparand Data area name Key Field

Resulting Ind. -ER

--

---

ER ER

---

--

ER

--

KLIST name Search argument Search argument Array name Table name Source field Source field Source field Source field Table name Target field Target field Target field Target field HI HI LO LO EQ EQ

143 of 148

MOVE (p) MOVEA (P) MOVEL MULT (1/2) MVR NEXT OCCUR OPEN ORxx OTHER OUT PARM PLIST POST (3) READ (n) READC (n) READE (n) READP (n) REDPE (n) REL RESET

Multiplicand Program Device Occurrence Value Comparand *LOCK Target field PLIST name Program device Search argument Search argument Search argument Program device *NOKEY

Source field Source Source field Multiplier File name

Target field Target Target field Product Remainder

+ + + + + -

ER ER ER ER

ZB ZB ZB Z Z -

Data Structure Occurrence Value File Name Comparand Data area name Source field File name File name, Record name File name, Record name File name, Record name File name, Record name File name, Record name File name Structure or Variable

Parameter INFDS name Data Structure Data Structure Data Structure Data Structure Data Structure ER ER ER ER ER ER ER EOF EOF EOF BOF BOF -

144 of 148

Codes RETRN ROLBK SCAN (2) SELEC SETGT SETLL SETOF (1) SETON (1) SHTDN SORTA SQRT (1/2) SUB (1/2) SUBST (p) TAG TESTB (1) TESTN (1) TESTZ (1) TIME UNLCK

Factor 1 Comparator string : length Search argument Search argument

Factor 2 Base string : start File name File name

Result Field Left-most position

Resulting Ind. ER ER FD

NR NR OF ON ON

ER ER OF ON ER ON BN ER ER ER ER -

EQ OF ON Z EQ BL EOF Z Z Z

Minuend Length to extract Label

Array name Value Substrhend Base string : start Bit numbers

Root Difference Target String Character field Character field Character field Numeric field

+ OF NU -

UPDAT WHxx Comparand WRITE XFOOT (1/2) XLATE (P) From :To Z-ADD Z-SUB Legend: (1) (2) (3) (P) (1/2) (n)

Data area, record or file name File name Comparand File name Array name String :start Addend Subtrahend

Data structure Data structure Sum Target String Sum Difference

+ + +

At least one resulting indicator required. A found indicator is required if the result field is not specified. You must specify factor 2 or the result field. You may specify both. Pad the result with blanks. Half adjust the result. No lock. 145 of 148

146 of 148

Appendix B : AS/400 Data Limits

AS/400 Data limits: Bytes in one record Fields per record Key fields in one record Keysize in bytes Records in one file Bytes in one file Database size Logical Files (Views) from one physical file Physical files used in one Logical File (View) Maximum files in a JOIN Maximum field size in bytes Maximum decimal number 32,766 8,000 120 256 16,777,215 2,147,483,648 size of disk storage 3,686 32 32 32,766 9,999,999,999,999,999,999,999,999,999,9 99

147 of 148

Appendix C : RPG/400 Restrictions
Function
AN/OR lines (positions 7 and 8 of calculation specifications) Arrays and tables Array/table input record length for compile time Character field length Control fields (position 59 and 60 of input specifica-tions) length Data structure length Data structure occurrences (number of) Edit Word Elements in an array/table (positions 36 through 39 of extension specifications) File Levels of nesting in structured groups Look-ahead Named Constant Overflow indicator Parameters Primary file (P in position 16 of file description specifications) Printer file (PRINTER in positions 40 through 46 of file description specifications) Printing lines per page Program status data structure Record address file (R in position 16 of file description specifications) Record length for program described file (positions 24 through 27 of file description specifications) Structured groups (see levels of nesting) Subroutines Tables (see arrays) Any device record size restraints override this value. Maximum of 254 per program.

Restriction
Maximum of 7 per operation. Maximum of 200 per program. Maximum length is 80. Maximum length is 256. Maximum length is 256.

Maximum of 9999. Maximum of 9999 per data structure. Maximum length of 24 for literals or 115 for named constants. Maximum of 9999 per array/table.

Maximum of 50 per program. Maximum of 100. Can be specified only once for a file. Can be specified only for primary and secondary files. Maximum length of 256 for character named constant, 512 for hexadecimal named constant, and 30 digits with 9 decimal positions for numeric named constant. Only 1 unique overflow indicator can be specified per printer file. Maximum of 255 Maximum of 1 per program. Maximum of 8 per program.

Minimum of 2; maximum of 112. Only 1 allowed per program. Only 1 allowed per program.

Maximum length is 9999.

148 of 148