Sei sulla pagina 1di 70

Course Number: AS 3005 (new topics)

OS/400 Basic Concepts Duration: 2 Days

Object management terms


Libraries Objects Members Sources Spool Files Output/Messages/Job queues Device Descriptions

Library
Libraries provide a method for organizing objects. All libraries are stored under QSYS library. We cannot have a library within a library (only exception being IBM supplied QSYS). All AS/400 objects should be stored in a library. A library is similar to a directory or a folder in the conventional file system (DOS/WINDOWS).

Object
On the AS/400, a wide variety of entities are objects -- files, programs, libraries, user profiles, commands, etc. A library contains object name, type (*PGM, *FILE, etc.) and a system managed (transparent) address. Objects must be unique, by name and type within a library.

Member
Data is stored in member(s) in a file. A file can have multiple members. The record format of the file is common across all the members of a file.

Summary Source file


A source file is a file where the source codes are maintained. Source code is stored as a member in a physical file. This file is called as a source physical file and is a customized version of a physical file.

Spool files
Printed output from any program is normally placed in a spool file. These spooled files can be displayed or can be printed. An output Q is an object containing a list of spooled files. Object type is *OUTQ. A Job Q contains the list of batch jobs waiting to be processed.

Output Q & Job Q Work Management Summary Message Q


All messages on the AS/400 are sent to message Qs. Types -- System supplied message Q, Workstation message Q, Job message Q, Program message Q and User message Q.

System supplied message Q -- QSYSOPR, supplied by IBM. Workstation & User message Q -- Allocated to user's job at sign-on. Job message Q -- for every job in the system. Program message Q -- for every program started within a job. A device description is needed to describe a device to the system. A device may be a diskette, optical device, display device, etc. Jobs Subsystems Job Descriptions Library Lists Job Logs Scheduling Activation Groups Interactive Processing Batch Processing A subsystem is a predefined operating environment. Subsystems manage resources. System can contain many subsystems tailored for different needs.

Device descriptions Job management terms

Subsystem Library list


A library list is an ordered list of libraries. These libraries are searched one by one until an object is found with the specified object name and type (If the object name is qualified by preceding it with a library, the system searches for the object only in the specified library).

Job
list. Each piece of work on the system is considered to be a job. Each job has a unique name within the system. Job name consists of a Job Name, Device and Job Sequence no. Job name is same as device name for interactive jobs. A job description is a collection of job related attributes - like job priority, date format, library Same job description can be used by multiple jobs.

Job Descriptions Job log


Job log contains information related to requests entered for a job, such as commands in the job, commands in a CL program, and messages.

Scheduling
The job schedule function allows for time-dependent scheduling of AS/400 batch jobs. Job scheduling allows you to control the date and time a batch job is submitted.

Activation groups
An activation group is a substructure of a job that contains the resources necessary to run the programs. Used to provide some level of isolation and protection from accidental access.

Interactive job
An interactive job is a job that starts when a user signs on to a display station and ends when the user signs off.

Batch job

A batch job is a predefined group of processing actions submitted to the system. A batch job will be performed with little or no interaction between the user and the system.

Batch job Cont....


A batch job is submitted from an interactive job normally and typically requires a special system environment to run.

Messages
System Compiler User Program

Messages
On the AS/400 system, communication between procedures or programs, between jobs, between users and between users and procedures or programs occurs through messages. A message is always sent to a message Q. A message can be predefined or immediate.

Predefined Message
A predefined message is created and exists outside the program that uses it. Predefined messages are stored in message files and have a message number. Immediate messages are those that can be composed on the fly.

Immediate Messages Predefined Vs Immediate Messages


Predefined messages -- provides standardization, runtime customization, no recompilation required if a message is changed, write once - use many times, second level text. Immediate messages -- compose on the go, can use SNDMSG, SNDBRKMSG.

System messages
An example of a system predefined message is CPF0006 - Errors occurred in command. System messages are stored in the file QCPFMSG in the library QSYS. Use SNDMSG or SNDBRKMSG or SNDUSRMSG to communicate with the system users.

User messages Program messages


Messages can be sent from one program to another program within a job using SNDPGMMSG. Job and program message Qs are automatically created and deleted as jobs and programs begin and end.

Message types
Inquiry -- message is displayed in break mode and the receiver of the message has to enter a reply. Normally sent to the external message Q. Notify -- normally used in CL programs to notify the user that a certain error condition has happened. This message can be sent only to a program message Q or to the external Q of the current job.

Message types ...


Informational -- This message is for informational purposes and does not wait for a reply. Can be sent to any message Q. Status -- Used to report the status or progress of a job. Can be sent only to a program message Q or to the external message Q.

Message types ...


Escape -- This message is sent to a program message Q indicating that the program terminated abnormally. Difference between notify message and escape message is that an escape message indicates an unrecoverable error while notify message indicates that the error can be corrected.

Message types ...


Completion -- message to indicate completion of a program. Can be sent to any kind of a message Q. Diagnostic -- Diagnostic messages are sent upon detection of error conditions during the execution of program. Can be sent to any kind of message Q.

Message types ...


Reply -- When a reply is sent for an inquiry message, it is a reply message. Request -- A message that requests a function from the receiving procedure or program. (For example, a CL command is a request message.)

Message type to Message Q CL Commands


ADDLIBLE -- Add library list entry -- to add a library to the user portion of the library list. By default the library is added on top of the existing library list. EDTLIBL -- Edit library list -- to edit the current user portion of the library list. New libraries may be added, libraries in the current list may be removed and the positions of the libraries may be changed using this command. SBMJOB -- Submit job -- to submit a job for batch processing into a job Q. Jobs that need minimum or no interaction from the user and long running jobs are normally submitted as a batch job. System would send a completion message once the job is over. CRTLIB -- Create library -- to create a new library. CHGCURLIB -- Change current library -- to set a library as the current library. If a current library is not set, the default current library is QGPL. DSPMSG -- Display message -- to display the messages from a specific message Q like workstation message Q, user message Q or QSYSOPR. DSPJOB -- Display job -- to display the details pertaining to a job - like job start date, current status, files used, programs running, spool files, library list, etc. WRKSPLF -- Work with spool files -- to display/print/delete spool files. WRKSBMJOB -- Work with job submitted from the workstation, job or user profile -- to display, change the submitted jobs (jobs running in batch). CRTSRCPF -- Create source physical file -- to create a source physical file. Source physical file is a customized version of a physical file, its record length is normally 92. This file is used to hold the source codes. CHGJOB -- Change job -- to change the run time parameters of a job - like job Q, priority, scheduling, output Q, date format, etc. CRTPGM -- Create program -- to create a program object from a set of modules. CRTRPGMOD -- Create RPG module -- to compile the RPG source into a module object (*MODULE). CRTRPGPGM -- Create RPG program -- to start the RPG compiler. DSPJOBLOG -- Display job log -- to display the job log - lists the commands used in the job so far and the messages. MOVOBJ -- Move object -- to move an object from one library to a different library (that is the object is removed from the current location and placed in a different library). STRDBG -- Start debug -- to start debugger -- puts a job (and adds programs) into debug mode. STRISDB -- Start interactive debugger -- to start the interactive source debugger. This command provides an interactive debugging environment for CL, RPG and COBOL programs. STRPDM -- Start Program development manager -- to start Program Development Manager - an application development tool provided along with the AS/400. WRKUSRPRF -- Work with user profile -- to maintain the user profiles. User profiles may be added, changed, deleted with this command.

WRKACTJOB -- Work with active job -- to work with performance and status information for the active jobs in the system. WRKUSRJOB -- Work with user job -- to work with a selected user jobs. WRKMSGF -- Work with message files -- to maintain the message files. This command may be used to create, change (the message descriptions) and delete a message file. UPDPGM -- Update program -- This command may be used to replace the modules in a bound program with other modules. The bound program need not be recompiled when a module is replaced.

AS/400 Security concepts


Security is always active on the AS/400. Authority is checked each time before an object is touched. To access any resource from the AS/400, a user ID and a password is necessary. At the lowest level, security can be implemented at the field level for a file. Level 10 -- Non-secured system. Level 20 -- Password required. Level 30 -- Full resource security. This is the level of security implemented in most systems. Level 40 -- Restricted access to system interface. This is to prevent unauthorized access through communications and APIs. The AS/400 system when shipped is at level 40. Level 50 -- Highest level of security. Intended to support the security standards set by US department of defense. Not used generally.

DDS
What is DDS ? Data Description Specifications ( DDS ) are a set of statements used to define OS/400 database and device file objects. It provides a field-level description of the contents of a physical, logical or a device file.

Files on AS/400
Database Source Device DDM Save AS/400 objects that actually contain data or provide access to data. Physical file. Type - *FILE Attribute - PF Logical file. Type - *FILE Attribute - LF To create use : CRTPF & CRTLF Customized form of a physical file where all the source members are maintained physical file having multiple data members To create use : CRTSRCPF

Database Files

Source Files

Device Files
Contain no actual data Files whose description provide information about how an application is to use particular devices Various types are display,printer,tape,diskette and ICF.

DDM Files
Distributed Data Management files are objects that represent files that exist on a remote system

Save Files
Special form of file designed specifically to handle save/restore data. Can be used to receive the output from a save operation and then be used as input for a restore operation.

Levels of Description
Object level File level Record level Field level All files are of object type *FILE Use DSPOBJD command to view the object level description of a file. Use CRTxxxF command to create the Printer and Display file Use CRTxF command to create the LF and PF Use DSPFD command to view the attributes and characteristics of a file Importance of File subtypes

Object Level Description File Level Description

AS/400 File Types and Subtypes Record Level Description


A Record Format describes a set of fields that make a record. All files have at least one record format Logical files can have multiple record formats Use DSPFD or DSPFFD command to view the record level information of a file A description for each field and its attributes Does not exist for all types of files Tape,Diskette,DDM and Save files do not have field descriptions. Use DSPFFD to view the field level descriptions of a file Overview PF is the file which contains the file descriptions and the related data. It supports only one record format They may be keyed or non keyed files Composite keys may be defined for a PF.

Field Level Description

PHYSICAL FILES Physical File ( PF )

Steps for creating a PF


Design a record format based on some application criteria. Write the code on a Data Description Specification (DDS) form Enter the DDS via Source Entry Utility (SEU) and save Compile,debug and store the error-free PF object

Keywords

While a PF is being created, there are many level of keywords that can be used that helps in creating and retrieval of records based on a specific condition. They are File level Record level Field level Key level

File Level Keywords


UNIQUE FIFO LIFO REF FORMAT TEXT ALWNULL COLHDG RANGE TEXT DATFMT DATSEP DESCEND Whenever a PF is created, it has by default one member. Maximum of 32,767 members can be created for a PF. All the members will have the same record format and field attributes of the PF. Each member will have different name for identification.

Record Level Keywords Field Level Keywords

Key Field Level Keywords What are Members ?

Where Members are used ?


Mainly used in user application that uses both current and historical data by a certain period. Using multiple data members provides a unique manner to handle data that uses the same record format and same field descriptions and yet must be maintained separately for business reasons.

Reference Files
A Field Reference File is a PF that is referenced by other externally described PF,LF,DSPF or PRTF for names and attributes of fields. They are created and compiled exactly like other PF but contain no data. This is done to reduce redundancy (ie) same fields defined in multiple PFs with sometimes different attributes.

Logical Files
Logical files do not contain any data. They are views of data contained in the physical file. Can have single or multiple record format Simple Join Self join To define a LF, first select the record formats to be used and the PFs to be referenced.

Types of LF Simple LF

PFILE

Existing record format in the PF can be used or a new record format can be defined If PF record format is used, every field in the PF is accessible through the LF. If new record format is created, then select the fields from the PF which will exist in the LF. A LF must know which PF it has to access for the data. This is the keyword used to select the PF referenced by the LF record format. Use qualified name in the PFILE Keyword.

Join LF
Can be based on from 2 to 32 PFs. Key fields, if specified must come from the primary file. These are read-only files and cannot be used to update files. Can have only one record format Important keywords to be used : JFILE JOIN JFLD JDUPSEQ JREF Used for joining a PF on to itself.

Self Join LF Select/Omit Logic


It is used to select or omit records from a referenced physical file depending upon the requirements. Keywords like COMP,VALUES and RANGE can be used. To use this, the LF should have a key field Select & Omit OR Relationship AND Relationship ALL condition

PF and its Impact on Data


How LFs get their data from PFs ? What happens when a PF which has LFs built over is deleted ? What happens to the LF when the PF is compiled ? Constraints can be used to enforce referential integrity of the data being processed. It is used to define dependencies between files. All Constraints are defined at the File Level.

PF Constraints

Types of Constraints
Referential Constraints Unique Constraints Primary Key Constraints Check Constraints

Access Path
Refers to a separate index built and maintained by the related LF.. May be built by LF to process the data stored in one or more PFs in an arrival sequence or in key-value order.

Access Path Maintenance


Whenever a LF is created, we should also specify the type of maintenance required for the access path. Three types of Maintenance are : Immediate

Rebuild Delay

Manipulation of Access Path


Manipulation of Access Path can be done using : OPNQRYF OVRDBF CPYFRMQRYF

FILE MANAGEMENT COMMANDS


Overview Disk space is very costly. Hence optimum use of it is advisable. It improves the overall system efficiency and performance.

Why is Management Required ? RGZPFM


Removes deleted records from a PF Optionally reorganizes that member. Physical sequence of the stored records in a member can be changed Optionally, new sequence numbers and zero date fields can be placed in the source fields of the records.

CPYF
Used to copy data and source files from database files. Data can be copied from PF and LF whereas data can be copied only to a PF. Copy data and source files from external devices like tape,diskette etc. Option of creating the to-file during copying.

DLTF
This command is used to delete one or more files from the system. If a PF or LF is deleted, all the members for the file is also deleted. All the LFs based on a PF has to be deleted before deleting the PF. SQL Views based on a PF has to be deleted before deleting the PF. This command is used to remove data from a member of a PF.

CLRPFM ADDPFM
This command is used to add a named member to an existing PF. The maximum number of members that can be added depends on the value given to the parameter MAXMBRS in CRTPF command. The value is 32,767.

ADDLFM
This command is used to add a named member to an existing LF. Each member can have its own data and can have its own access path.

CRTDUPOBJ vs CPYF
CPYF command is used only for object of type *FILE whereas CRTDUPOBJ can be used for any type of object.

Database Modeling And Design

Logical Data Modeling . Produces a description from the business perspective. Process Modeling- System design. Naming Standard. Naming convention should be consistent and should express clearly what an item represents or stores.

Valid abbreviations. Valid names. Preferred usage. Description. Data Dictionary A data dictionary is a container to record everything during the modeling process. The containers may be: Word processing documents. Database files. Design tool project folders. Identify Entity Types. The factors to be considered to identify Entity types: Official name for the entity type. Synonyms. Short textual description. Approximate or estimated yearly volumes. Entity type hierarchies.

Entity Properties. Entity Properties can be classified into: Single-valued property. Multivalued property. Time-dependent property. Direct property. Derived property. Primary Key- Entity Relation. Primary key must be unique for each row in the table. It must never be missing or incomplete for a row. It should be meaningless. Primary key should never change. There should be no limit to the number of primary key values available. Only one primary key should be specified for each table. Relationships between Entity Types. The Entity identified are mostly interrelated. The three major categories of cardinality are: One-to-one. One-to-many. Many-to-many.

Foreign Key- Entity Relation.


Customer Integrity Constraints. Domains. Predicates. - Multirow predicates. - Multitable predicates. Transition Constraints. Assertions. Triggered Procedures. Security Rules. Value-independent rule. Value-dependent rule. Statistical rule. Context-dependent rule.

In a data model, a primary key of the parent entity becomes the foreign key in the referenced or dependant entity. Order

Multiple Users Views.

Users view are referred to as Subschemas or External schemas.

Integrated model is the schema or conceptual schema. Integrating multiple views involves : Identifying columns. Resolving domain. Synthesizing the schemas base tables.

Schema Base Tables

Schema base table redundancy can be eliminated by: Check on the result of the integration of multiple users view. Check each table to see that it does not violate any of the rules of normalization. Check all columns to see whether they can be derived from from other columns.

Subschema Views
Restriction- subsetting of rows. Projection- elimination of columns. Combination of rows- joins or unions from more than one table. Derivation of virtual columns that are a function of columns in underlying base tables. Ordering- sorting of rows in a view.

Debugging Error Classification


Compile-time Errors Run-time(Execution) Errors

RPG-IV Programs

Compile-time Errors
Syntax Errors Ex. Placing an Entry in the wrong field, Undefined Fields and Indicators etc. Some Syntax Errors will be flagged by the SEU when the instructions are entered and force the Programmer to make necessary change(s). Severity Errors are generated during compilation of the program. Severity Errors are classified as Information(00), Warning(10), Error(20) or Severe Error(30+).Severity Error =>20 stops compilation. One Syntax Error may cause more than one Severity Error. All Compile Errors should be Reviewed though some may be ignored.

Run-time Errors
Halts/Abnormally ends the program execution. Data or Logic Errors. More difficult to find Examples: 1. Divide by Zero 2. Never-ending Loop 3. Conditioning an instruction with wrong Indicator 4. Unconditional Branch 5. Incorrect Output Results

Working with the Spool File


Compiled Program creates a Spool File Compilation OK - Program has been Created message at the File bottom Compilation Error 1. Check Error code and Trace in the Source area. Error Description gives the problem in the line of code. 2. Go back to the PDM edit screen and correct the error. 3. Recompile the program. 4. Continue the above process till the Compilation is OK and the Program has been created message is obtained.

Interactive Debugging

Used to locate Run-time Errors that does or does not cause Program dump. The Interactive Debugging session is started using the STRDBG (Start Debug) command Debugging Views: *SOURCE, *ALL, *COPY, *LIST, *STMT Setting and Removing Break Points Stepping through the Program Object Displaying Data and Expression Displaying Contents of Array, Table and Data Structure Displaying Indicators Displaying Field Attributes Changing Field Values Equating a Name with a Field, Expression or Command Using Debug Built-in Functions

Debugging Functions

Break Points
Used to halt the Program Execution at a Specific Instruction Types: Conditional -Stops Program Execution when the specified condition occurs. Breakpoint Occurs for an
Instruction after the Conditional Expression is Evaluated Unconditional -Stops Program Execution at a Specific Instruction. Break Point Occurs before the Related Instruction is Executed

Stepping Through Program Object


Once the Break Point is encountered a specific number of instructions may be run and the program stopped again. The Step may be one single instruction (F10) or a set of instructions

Displaying Data, Expressions and Indicators


by

Data stored in a Field, Data Structure, Array or Table and an Expression may be displayed
Placing the cursor on the variable and pressing F11 key Entering the EVAL Variable-name debug command on the Debug line of the Screen

Indicators are displayed by the EVAL *IN command on the Debug line of the Screen

Built-In Debugger Functions


%SUBSTR - Substring a string field %INDEX - Change the Table Index or multiple-occurrence Data Structure %ADDR - Retrieve the Field Address

Ending the Debug Session


After the Debugging session is completed for a program, end it by ENDDBG command Debugging another program or the same program again without entering the ENDDBG command will trigger the error message Command STRDBG not valid in this mode.

DATA FILE UTILTY


Used to perform operations on data files. Operations include 1. Changing data 2. Adding records 3. Deleting records Indexed and non-indexed files can be manipulated using DFU. DFU can create temporary or permanent programs to modify the data in a file. DFU can be invoked in three ways. 1. From main menu option4, DATA menu appears. From that menu option 1 gives FILE menu. Option 7 in this menu is DFU. 2. By command STRDFU from any command prompt 3. From Programmer Menu(can be obtained by STRPGMMNU), option 1 results in DFU.

STRDFU Command STRDFU command uses the information from last DFU session. SRTDFU on command line and <F4> prompts for different parameters. 1. DFU Option : It can take any value between 1 and 5 or *SELECT. The default value is *SELECT. 2. Run option : It can take values 1 or 2 or *NONE. 3. DFU program and library : DFU program needs to be specified and its library. It is not mandatory.

4. Data base file, library and member : The data file which needs to be processed is given here with its library name and member. The DFU main menu will be shown if *SELECT option is selected from STRDFU command at DFU option DFU main menu has the options as shown in figure. Option 1 runs a DFU program which is already present. Option 2 creates a DFU program which can be run later. Option 3 can be used to change an existing DFU program. Option 4 is used to delete an existing DFU program. Option 5 is used to make use of a temporary program to run the command.

Create a DFU To create a DFU program, give STRDFU and option 2. Create a DFU Program screen appears. Name of Program to be created and File on which it is created needs to be given. Define General Information screen appears. The parameters in this screen are Job title, display format, The parameters in this screen are Job title, Display format, Audit report(Y/N), S/36 style(Y/N), Suppress records(Y/N), Edit numbers(Y/N), Allow Update on roll(Y/N), Record Numbers options and Processing(1/2). After above information is given, Define Audit Control screen appears. The parameters in this screen are Print additions(Y/N), Print changes(Y/N), Print deletions(Y/N), Printer settings such as Line width and Column spacing which govern the format of the Audit report. After these values are entered, Work with Record Formats screen appears where a record format selection is done. After this screen, for selected record formats, Select and Sequence Fields screen appears where the sequence of the appearance of fields is entered. After this screen, Work with fields screen appears where each fields definition can be extended by selecting option 2. Heading, Allowing of lower case and Initial values can be specified. Running a DFU A DFU program is run by STRDFU command and option 1. A DFU program can be run to display the data or to change the data.

Changing Data using DFU The data can be processed even if a DFU program is not available before. That is achieved by executing command STRDFU and option 5 would create a temporary DFU program with default options to process the data. Screen WORK WITH DATA IN A FILE appears. Press ROLL UP or ROLL DOWN keys to view the data. The corresponding record number would be displayed.

<F6> function is used to select a particular record format. <F9> function key is used to insert the data at the current location. The data is inserted at the end of the file for sequential processing. <F10> function key is used to enter the data at the end. <F11> function key is used to change the data at a particular record number or the data of a particular key value. <F23> function key is used to delete an appearing record. <F15> is used to print the current record. <F20> is used to set automatic advance to the new record after the last field in the record is filled to on or off. <F21> is used to see the status of the running DFU program. <F22> is used to turn on or off automatic duplication. Press <F18> to turn automatic increment on from the last record changed. Press <F19> to turn automatic increment on from the end of the file.

Programming Development Manager


It is a list-oriented interface for working with different objects, including libraries, members in a file. Allows access to SEU, DFU and SDA. Provides a user-defined option mechanism where your own commands and IBM system commands can be used on the objects in the list. Furnishes a grouping technique that allows you to subset a list of objects. Can be invoked through the start PDM (STRPDM) command or from the Programmer Menu (STRPGMMNU command). Available options with the PDM are: 1. Work with libraries 2. Work with objects 3. Work with Members 9. Work with user defined options 1 - executes Work with libraries using PDM (WRKLIBPDM) 2 - executes Work with objects using PDM (WRKOBJPDM) 3 - runs Work with members using PDM (WRKMBRPDM) 9 - changes the user-defined options associated with PDM. PDM provides common actions, functions and common interface among the four PDM selections. The common actions are accessed through the use of options selected from the listoriented interface. The common functions are accomplished through the use of standard, common and specific function keys The common interface is a list oriented interface that displays the objects to be accessed in a list. THE LIST ORIENTED INTERFACE: The list oriented interface of PDM provides a common method of accessing objects. An option area is provided for each object in the list Multiple options can be selected for objects in the list

The actions to be performed by the option selected will be performed on each object in sequence, from the top to the bottom of the list SUBSETTING A LIST: The <F17> key subsets the list of displayed objects. A display is shown containing the appropriate selection criteria for the type of object being accessed. Any of the criteria can be used for subsetting the list. The special value *ALL can be used to have PDM accept any value for the entry. FUNCTION KEYS: Three types of function keys are used in PDM: Standard function keys - used with most OS/400 commands Common function keys - specific to PDM but provide common function Specific function keys - only appropriate for a specific PDM selection The Standard function keys: <F1>/<HELP> - Provides General or context sensitive help <F3> - Exits PDM or stops a function with no action taken <F4> - Prompts a command entered on the command line <F5> - Refreshes the screen and rebuilds the list <F9> - Retrieves a previously entered command from the command line <F12> - Cancels the current function and returns to the previous display <F23> - Displays the options not currently displayed on the screen <F24> - Displays the function keys not currently displayed on the screen The Common function keys: <F4> - Prompts the command associated with the option and places any available information in the appropriate keywords for the command <F6> - Creates a new object based on the type of object being created. <F10> - Displays the command entry screen <F11> - Changes the information displayed in the list. <F11> is a toggle key, meaning the display changes between a multiple column display of object names only or a display of single column list of names, types and text description. <F13> - Repeats the action performed by an option entered in a previous list entry. The action is performed for all the remaining entries in a list for which the option is valid. <F16> - Displays the Work with User-Defined Options screen. <F17> - Subsets the list being displayed. <F18> - Changes the defaults associated with the PDM session. <F21> - Prints the current list of objects Specific function keys for the WRKOBJPDM: <F6> - Displays the Create Commands menu to allow you to select the appropriate command for creating a new object <F14> - Displays the size or the attribute of the object. <F14> is a toggle key, meaning either the sizes or the attributes or the objects in the list will be displayed. Specific function keys for the WRKMBRPDM: <F6> - Invokes SEU to allow you to create a new source member <F14> - Displays the date or the type of the member. <F14> is a toggle key, meaning either the dates or the types of the members in the list will be displayed

<F15> - Sorts the display by date or member name. <F15> is a toggle key, meaning the display will be sorted by date or by name. WORKING WITH USER DEFINED OPTIONS: Allows manipulation of options that are defined in place of or in addition to the options provided by PDM. The default user-defined option file is QUAOOPT in library QGPL with member QUAOOPT. - Contains user defined options as they are shipped from IBM. - New user-defined options can be added. Each user-defined option executes a command by establishing an interface between the user-defined option and the information contained within the list entries. The display shows the option and its associated command. Specifying an option in the Opt field allows manipulation of the user-defined commands Available options are: 2 - Changes an existing user-defined option 3 - Copies a user-defined option to a different option 4 - Deletes a user-defined option 5 - Displays a user-defined option The specific function keys for this display are: <F6> - Creates new user-defined option <F15> - Exits option manipulation without saving changes Selecting option 2 allows to change an existing or create a new user-defined option The option parameter can be any character value The command parameter can be any command and will be executed when the option is specified next to a list entry PDM provides an interface between the list entry and the command through the use of special characters used as substitution parameters. The substitution parameters would be used as arguments to the command that is to be executed. The special characters are: &A - Object Attribute &B - List Type (L - List of libraries, O - List of Objects etc.) &C - Option (&C is replaced by the user-defined option code) &D - Member/part change date &E - Run in batch (Y - *YES, N - *NO) &F - File Name &G - Job description library &H - Job description name &J - Job description &L - Library name &N - Item name &O - Object library

&P - Compile in batch (Y - *YES, N - *NO) &R - Replace object (Y - *YES, N - *NO) &S - Item type without * (Ex: LIB for Library) &T - Item type with * (Ex: *LIB for library) &U - User-Defined Option File &V - User-Defined Option Library &W - User-Defined Option File Member &X - Item text

Query Manager
The Work with Query Manager Queries is used for all query operations: creating, changing, running, or using a query in any way. It can be invoked by command STRQM at command line. A new query can be created or an existing query can be updated. The screen has different entries for defining a query. Selection of files used in query, new field definitions, selection of records on particular criterion, sorting selection, summary functions and report formatting is done by different selections in the screen. Files on which query is run is specified in this selection. By giving + in third field, multiple files selection can be done. When more than one file is selected, join condition needs to be specified. The Specify Join Conditions screen appears as soon as the second file is declared and pressed <Enter>. In the Specify Join Conditions screen, the criterion for joining the files is given. The criterion can be given by using field comparison of both files fields. Loop joining cannot be done like A joining B, B joining C and C joining A. In this screen, new fields would be created with some operations on existing fields. New field would be created with expression using arithmetic operations such as *, +, -, / on numeric fields. New Non-numeric fields would be created by using CONCAT and SUBSTR. CONCAT is used to concatenate two fields. SUBSTR has format SUBSTR(field,pos,len) here field is the name of the field, pos is the pos from which string needs to be taken, Len being the length of the string needs to be taken. IF Len is not specified, the remaining field from the offset is taken. This screen would be used to select the fields to be displayed in the query. The newly defined fields by previous option would also be listed for display. The sequence numbers would be given to govern the order of display. This screen is used to make selection depending on some condition met. Logical AND and OR are used for specifying multiple conditions. Operations GT, LT, GE, LE, EQ are used for building conditions. This screen is used to make selection for sorting records based on some fields. The fields and the order (Ascending/ Descending) is selected from the screen. The primary key is given least value against it and secondary key the next higher value and so on. The summary functions are Sum, Avg, Min, Max, Cnt.

Sum is used to calculate total for a numeric field against which selection is made. Avg is used to calculate average for a numeric field against which selection is made. Min is used to find the least value in collating seuence. Max is used to get the maximum value in the selection. cnt gives the number of records which met the condition. Option 1 would return duplicate records if present whereas option 2 would return only first record in duplicate records. This display is used to select a report form to work with. An existing form can be specified or a new form can be created. New form would be created if the given form does not exist. In Define Prompted Query screen, pressing <F18> would display the SQL statement which would be run. Query Manager statements such as connect, commit, save, run etc can be given on QM statement line which would be got by pressing <F22>. The query till the selection has been made can be run by pressing <F6>. The query can be saved by pressing <F3> and giving option 1 in Exit screen and specifying the name and library. The saved query can be run by giving option 9 in the main screen against the query name.

Screen Design Aid Creates, modifies and tests display files and menus. Is an interactive method for creating DDS for a display file or menu. Display files are the interface between a program and the user. Menus provide a method of choosing programs or commands to execute. Can be invoked through the Start Screen Design Aid (STRSDA) command or from the Programmer Menu (STRPGMMNU command). Select option 1 from SDA to create and update display files, through Work with Display Records screen, which shows the records that are contained within the selected member, file and library. Available options with the Work with Display Records display are: 1 - Adds a new record 2 - Edits Comments associated with the record 3 - Copies an existing display record to a new record name 4 - Removes an existing display record from the member 7 - Renames an existing display record 8 - Select DDS keywords for the display record 12 - Design an image by changing an existing display record The function keys used on this display include the standard function key with the addition of <F11> - Displays the text associated with the member <F14> - Changes the file-level DDS keywords for the member <F15> - Changes the file-level comments <F17> - Subsets the list of display records

Selecting option 1 causes Add New Records display to be shown. Values must be specified for Name of the new record and the type of record. Valid record types are: RECORD A Display Record (most common) USRDFN A user defined display record SFL A Subfile record SFLMSG A Subfile message record WINDOW A Window record WDWSFL A Window subfile record PULDWN A Pull-down record PDNSFL A Pull-down subfile record MNUBAR A Menu-bar record MANIPULATING A RECORD FORMAT: Blank screen appears when creating new record format The screen image appears when changing an existing format The screen is a design area where fields and constants are positioned and attributes assigned. Function keys available when designing a screen include: <F3> - Ends screen design and proceeds to the Exit Design Image screen <F4> - Shows the work with fields display for attribute selection. <F6> - Shows the condition Work screen display for specifying indicators that condition record display for the design process. <F9> - Provides for selection of additional records to be shown on the display in the design process. <F10> - Shows the Select Database Files display to select a file from which field definitions can be copied. <F11> - Displays the list of database fields on the bottom row of the screen. This key is a toggle <F12> - Saves the work and returns to the Work with Display Records display. <F14> - Displays a horizontal and vertical ruler. This key is a toggle. <F15> - Prompts for subfile information. <F17> - Prints the contents of the Design Image Screen. <F18> - Moves the cursor to the attribute position of the next field. <F19> - Moves the cursor to the attribute position of the previous field. <F20> - Displays the constants in reverse image. <F21> - Displays additional selected records on the screen. This key is a toggle ADDING AND DELETING FIELDS AND CONSTANTS: Fields are added by entering a plus sign followed by the format code for the field type desired, followed by the length of the field in parentheses. The format codes for different field types are: Alphanumeric Numeric Field Usage I 3 Input only O 6 Output only B 9 Both input & output

Constants are added by typing the constant onto the design screen in the position desired. Constants consisting of several words can be defined as a single constant by placing single quotation marks around the group of words. System-defined constants can be placed in any valid location on the display screen. The predefined constants are *DATE - Provides the system date *TIME - Provides the system time *USER - Provides the current user name *SYSNAME - Provides the system name SPECIFYNG ATTRIBUTES AND COLOR: The attribute codes are placed in the character position immediately preceding the field or constant List of attribute codes: B - Blink H - High Intensity N - Non display R - Reverse Image S - Column Separators U - Underline Color attribute Codes: CB - Blue CG - Green CP - Pink CR - Red CT - Turquoise CW - White A - followed by the attribute code in the attribute position of the field or constant will remove the attribute. -A removes all attributes. -CA removes all colors. A * in the attribute position and <ENTER> leads to extended field definition display allowing entry of attributes. A ? in the attribute position and <ENTER> shows the field length, type and field name. The field can be renamed with this method. A Field/constant can be deleted by spacing over it or by placing D in the attribute position and pressing <ENTER>. A Field can be centered in the same row by placing AC in the attribute position and pressing <ENTER> A Field/Constant can be moved by placing - in the attribute position and = in the target position and pressing <ENTER> A Field/Constant can be copied by placing - in the attribute position and == in the target position and pressing <ENTER> Fields and Constants are shifted using < and > characters ADDING FIELDS FROM A DATABASE FILE: Access the Select Database Files display with <F10> Identify the database file, library, and record format name Four options are available for selecting fields 1 - Provides a list of fields in the database file 2 - Selects all fields as input fields 3 - Selects all fields as output fields 4 - Selects all fields as input/output fields

Selecting option 1 causes Select Database Fields display to be shown. <ROLL UP> and <ROLL DOWN> keys can be used to page through the field list. There are four options to select the fields and fields can be selected as different types. 1 - Provides an extended description 2 - Selects the fields as input fields 3 - Selects the fields as output fields 4 - Selects the fields as input/output fields Selected fields are shown on the bottom of the design screen Positioning the fields: Positioning codes are placed on the design screen at the position where the fields should be located. & or &n - Positions the database field but doesnt add Column Heading &C or &nC - Positions the database field and centers the Column Heading above the field &L or &nL - Positions the database field and adds the Column Heading to the left of the field &R or &nR - Positions the database field and adds the Column Heading to the right of the field &P or &nP - Positions the Column Heading only SAVING AND EXITING: The <F12> key saves the current records and returns to the Work with Display Records screen. The <F3> exit key shows the exit SDA work screen display where you can save the changes, exit without saving, or return to the design screen. CREATING A MENU: A menu consists of a display screen containing the menu text (an object of type MNUDDS) and an associated file that contains the commands to be executed (an object of type MNUCMD). Option 2, Design Menus, from the SDA Main Menu shows a display requiring values for a Source file, Library name and Menu name. The specify Menu Options screen will then be displayed. The screen requires a value for the work with menu image and commands prompt (usually Y). This allows entry of the menu text and the associated menu commands. Creating a new menu causes a blank screen to be displayed Revising an existing menu causes the selected menu to be displayed. The supplied options can be used or a free format menu can be created. Option numbers must be in the range of 1 - 99 The default format has the menu name in the upper left corner of the screen and the menu title centered over the menu options Command text is entered as with designing a screen including all the properties (Attributes, Positioning etc.). System supplied predefined constants can also be used. <F13> is used to work with the command area, which is the area at the bottom of the screen where the option and commands are entered.

The default text for command line is Selection or Command. The default can be changed by over typing the text. The location of the command line is determined by create menu (CRTMNU) option. <F10> displays the Define Menu Commands screen. This display contains, the command to be executed when the corresponding menu option is selected. The <F11> key only displays menu options that have been already defined. Next to each option number is a command line. The <F4> key can be used to prompt the command to provide the appropriate command parameters. Placing a ? in front of the command provides command prompting when the menu option is selected. Source Entry Utility The source editor on AS/400 is SEU. With this utility the source member in a source physical files can be edited. For RPG, DDS, CLP the SEU can check the 1st level syntax. It can be invoked in four ways. 1. From main menu, option 4, 1, 4. 2. By STRSEU command. 3. From STRPGMMNU command 4. From STRPDM command STRSEU is the direct command. It remembers the previously entered values and they become the default. The parameters for it are source file, library, source member, source type, option and text. SEU type can take different values. The commonly used types are CBL CLP CMD CL DSPF LF MNU PF PRTF QRY RPG SQLRPG TXT A blank member appears if the entered member does not exist. If the member exists, the existing member would be shown.

F1 = Help F3 = Exit F4 = Prompt F5 = Refresh F9 = Retrieve F10 = cursor F11 = Previous Record F13 = Change session defaults F14 = Find/Change options F15 = Browse/Copy options F16 = Repeat FindF17 = Repeat Change F19 = Left F20 = Right F21 = System command F24 = More keys

A, An --- After, where n is number of Lines B, Bn --- Before, where n is number of Lines C, Cn, CC, CR, CRn, CCR --- copy line COLS --- Display columns D, Dn, DD --- delete line F, Fff, F? --- Display format line I, In, IF, Ifn, Ifff, Ifffn, IF?, IF?n, IP, Ipff, IP?, IS, IS n --- Insert line L, Ln, LL, LLn, LT, LLT, LLTn --- Shift data left M, Mn, MM --- Move line O, On, OO --- Overlay P, Pff, P? --- Display prompt R, Rn, RR, RRn, RT, RRT --- Shift data right RP, RPn, RPP, RPPn --- Repeat line SF, SFn --- Show first record SL, SLn --- Show last record TABS --- set/display tabs W, Wn --- Window to line X, Xn, XX --- Exclude line +, +n --- Roll display forward -, -n --- Roll display backward x --- Go to line Prompting provides a split screen display where the upper part of the screen shows the code and lower part contains the prompt. Pressing <F4> on the code or giving line command P produces a prompt. The prompt can be selected for a particular format by giving line command IP?.

FIND (F) --- Find a string CHANGE (C) --- Change a string SAVE --- Save the member CANCEL (CAN) --- Cancel the changes FILE --- Save and Exit TOP (T) --- Go to member top BOTTOM (B) --- Go to member down SET (S) --- Set Environment options They will be used in the format SET <option> <on/off> The different options are MATCH --Force a match case CAPS --only uppercase entry TABS --Use tab settings ROLL --Determines roll mode EXPERT --Use expert mode SHIFT --Allows data to shift in CHANGE operation. The line numbers appear at leftmost portion.

When new line is inserted a number is allocated based on the value given in the option Increment of insert record in screen Change session defaults. When exiting line numbers can be rearranged by giving Y at option Resequence Number. For every session there would be some default values which govern the appearance. The defaults can be viewed and changed with function key <F13> The amount to roll, case appearance in typing, Increment line numbers for inserted records, Screen mode, source type, set records to date etc are the different control parameters. <F14> to enter to Find/Change screen. The parameters which can be controlled are Find string, change string, columns to search, processing occurrences, records to search, kind of match, data shift allowing in case of change. EXIT screen appears when <F3> is pressed in SEU screen. The parameters in the screen are Change/create Member(Y/N), Library file and Member to be saved in, Text, Re sequence Number(Y/N), Start number for Increment, Increment value, Print Member(Y/N), Return to Member(Y/N), Go to Member List(Y/N).

SQL This is used to communicate with data base management system. With SQL data manipulation such as display, insert, update and delete operations can be performed. It is an ANSII standard language. The SQL commands can be given on an editor which can be obtained by STRSQL command. SELECT statement is used for displaying all/certain columns. A simple select statements looks like this SELECT * FROM USRLIB/FILEA This would display all the records in with all the fields in FILEA. A complex SELECT statement looks like this. SELECT ENAME, ESAL FROM USRLIB/EMPMST WHERE EDEPT = AS/400 ORDER BY ENO The above statement would select the field values of ENAME, ESAL from EMPMST file for the records whose EDEPT value is AS/400 and they would be retrieved in the sequential order of ENO. The SELECT also has grouping on a field value, defining new fields, arithmetic expressions support, multiple conditions using logical operators like AND and OR. The output of a SELECT statement can be directed to a printer file or to a physical file. This done by going to screen Change Session Attributes by pressing <F13>. INSERT is used to create a new record with the values given. Ex : INSERT INTO EMPMST (ENO, ENAME, EDEPT, ESAL) VALUES(4023, KAMAL, AS/400, 25000) The values given in values braces are stored in corresponding fields. UPDATE is used to update one or more records in a file.

Ex : UPDATE EMPMST SET ESAL = 28500 WHERE ENO = 4023 This query updates the employee record for ESAL whose ENO is 4023. This statement is used to delete one or more records in a file. Ex : DELETE FROM EMPMST WHERE ENO = 4023 This query deletes the record whose ENO field value is 4023. The selection of files, fields, conditions etc can be selected by pressing <F4> on the query editor. The command to be used can be selected and the corresponding screen appears. The joining of two tables is done based on a common column values. Ex : SELECT * FROM EMPMST, EMPDET WHERE ENO = EMPNO This would select the records from Cartesian product where specified key is matching in the two tables. It is used for nested queries. A query selection is based on another queries output. Ex : SELECT * FROM EMPMST WHERE ENO IN (SELECT EMPNO FROM EMPDET) The above query gives details of all employees from EMPMST whose details are available in EMPDET. SQL statements can be included in a high level language. Ex : SQL used in RPGLE. C/EXEC SQL C+ DELETE FROM USRLIB/EMPMST C+ WHERE ENO = 4023 C/END-EXEC SQL statements would be written in C specification. Between EXEC SQL and END-EXEC the SQL statement would be written. An RPGLE program with embedded SQL statements would be of type SQLRPGLE and be compiled with CL command CRTSQLRPGI. The subset of records selected from an embedded query in a high level language program is called cursor. Ex : C/EXEC SQL C+ Declare Empcursor Cursor C+ For Select * From EMPMST order by ENO C/END-EXEC

C/EXEC SQL C+ Open Empcursor C/END-EXEC C/EXEC SQL C+ Fetch Next C+ from Empcursor C+ Into :ENUMB, :ENAM, :EDEPAT, C+ :ESALAR C/END-EXEC C/EXEC SQL C+ Close Empcursor

C/END-EXEC Declare is used to declare the name of the cursor followed by the SQL statement. Open statement is used to make the cursor ready to use in the program. Fetch statement is used to read the cursor records into the program fields which are given with : before them. Close statement is used to close the cursor. After a cursor is closed, records cannot be fetched from the cursor.

Control Language Programming


Course Number : AS3010 Duration : 4 Days

Chapter 01 CLP Structure


PGM Command Declare Commands CL Processing Commands Logic Control Commands

CLP Structure
Built-in Functions Program Control Commands The ENDPGM Command Comment Lines Labels in CPP

The PGM Command


Each statement in CLP is CL Command The PGM command used to Identify start of CLP Valid only within CLP Must be the First Command in the Program e.g. PGM PARM(CL-variable name) PARM indicates one or more parameters passed to this pgm from a CALLING pgm.

Declare Commands

All Variables and Files used in PGM should be Declared DCL is used to Declare Variables DCLF is used to Declare File Declare Commands should precede all other Commands except PGM

CL Processing Commands
CL Processing Commands used for

Manipulating Variables Copy Files, Sort Files Create Duplicate Objects Override with Database Files Send Program Messages Send and Receive Display Files

Send User Messages


Processing
CHGDTAARA CHGSYSVAL CHGVAR CPYF CRTDUPOBJ FMTDTA MONMSG RTVNETA , RTVSYSVAL

Most Frequently used CL Commands for CL



Logic Control Commands


Unlike traditional JCL, CLP allows the Use of Logic Control Commands Like IF, DO, and GOTO

Built-In Functions
Predefined Functions that allow CLP to perform special functions like

Setting Switches Manipulating character Strings Converting Data


Two Major Built-in Functions

%SWITCH %SUBSTRING

Program Control Commands

Program Control Commands are used to

Execute Programs Run Queries Pass Control to Other Programs


Examples of Program Control Commands

CALL TFRCTL RETURN RUNQRY

The ENDPGM Command



ENDPGM command is used to END program The Command is Optional It is valid only within CLP It is considered to be good practice to

Start program with PGM command End program with ENDPGM command

Comment Lines
Character pair /* and */ are used as Delimiters Example : /* This is a Commented Line */

Labels in CLP
Label Identifies the Statements in CLP to which Processing is Directed Used along with GOTO statement

Example :

GOTO END:

END ENDPGM

Declaring Variables

CL VARIABLES

Chapter 02

Declaration of Variable means

Declaration of Name of Variable Its Type Its Length Its Initial Value

DCL VAR(&variable name) TYPE(*DEC, *CHAR, or *LGL) LEN(length) VALUE(initial-value)

Declaration of Files
File used in CLP must be declared DCLF command is used for Declaration of File DCLF FILE(library-name/file-name) + RCDFMT(*ALL or record-format-name) Only ONE DCLF command is allowed in CLP DCLF is valid only within CLP

Changing Variables
CHGVAR command is used for changing the value of Variable To a Constant : CHGVAR VAR(&city) VALUE(Pune) To the Value of Another Variable CHGVAR VAR(&a) VALUE(&b) To the Value of an Expression CHGVAR VAR(&a) VALUE( &a + 20 )
CL EXPRESSIONS and OPERATORS

Chapter 03

EXPRESSIONS
Expression is a Group of Symbols used to express certain Values Examples of CL commands which use expressions: CHGVAR VAR(&var1) VALUE( 1 + 2 ) CHGVAR VAR(&var1) VALUE(&var2 + 3) CHGVAR VAR(&var1) + VALUE(&var2 +&var3)

Operators
Operators are Symbols that Instruct System to Perform Various Types of Basic Operations on Data Example : IF COND(&a *EQ &b) THEN(CALL pgmb) Operators can be used in a CLP to Specify the relationship between logical expression Operators indicate an action to be performed on Operands in Expression

Types of Operators
Logical Operators : *AND, *OR

Arithmetic Operators : +, -, *, / Character Operators : *CAT, || , *BCAT, | >, | <, *TCAT Relational Operators : *EQ, *GT, *LT, *GE *LE, *NG, *NL

Using Logical Operators


These are used to Specify the relationship between Operands in a Logical Expression Used to Evaluate True or False Condition Logical Expression usually contains 2 Operands These 2 Operands must be separated by a Logical Operators

Using Relational Operators


Examples : IF COND(&a = &b) THEN( CALL pgm1) IF COND(&a >= &b) THEN( CALL pgm2) IF COND(&a < > &b) THEN( CALL pgm3) IF COND(&a *LT &b) THEN( CALL pgm4)

Using Arithmetic Operators



Arithmetic operators are used for performing calculations in Arithmetic expressions Arithmetic expressions are often used

In COND parameter of IF command In VALUE parameter of CHGVAR command

Using Arithmetic Operators Examples


IF COND(( &a + &b) = &c) THEN ( CALL PGMA) CHGVAR VAR(&var) VALUE(&var * 10) CHGVAR VAR(&variable) VALUE(&variable / 400)

Using Character Operators



Character Operators are used for Concatenating 2 character string expressions In CLP, Character Operators are Used

In PRTTXT parameter of CHGJOB command VALUE parameter of CHGVAR command MSG parameter of SNDMSG, SNDBRKMSG,

SNDPGMMSG, SNDUSRMSG

Using Character Operators


*CAT : Concatenation *BCAT : Blank Insertion with Concatenation *TCAT : Blank Truncation with Concatenation Using Character Operators Examples CHGJOB PRTTXT(&var1 *BCAT &var2) CHGVAR VAR(&variable) VALUE(&city *TCAT &state) SNDMSG MSG ( Current time is : *CAT &SYSTIME) TOUSR(Prasad)

CL BUILT-IN FUNCTIONS

Chapter 04

Built-In Functions Offer



The SWITCH function is used to test JOB switches to Condition Processing The SUBSTRING function is used to manipulate character strings and to form a substring

%SWITCH Built-In Function


The 8 job switches used in CL are expressed as either 1 or 0 %SWITCH function is Used to test Job Switches that Condition Processing in CLP A Job Switch can have one of 3 Logical Values:

0 - OFF 1 - ON X - To be Ignored

% SWITCH in CLP
The 8 job Switches in CLP match the External Indicators U1 - U8 in RPG % SWITCH can be specified in COND parameter of IF command Example : IF COND ( %SWITCH ( 1XXXXXX1 ) ) THEN ( CALL rpgpgm1 )

%Substring Built-in Function


%SST function can be used to Manipulate a character string in a Character Variable to form a Substring To use a %SST function, variable should be declared as Character Example : %SST ( &DATE 1 4 ) 1 : Starting Position 2 : Length of Characters to be Extracted

% SST In CLP
%SST is usually specified in COND parm of IF command Example : IF COND( COND %SST ( &Variable 1 3 ) *EQ CTS)

% SST In CLP
% SST is usually used in VAR and VALUE parameters of CHGVAR command Example : CHGVAR VAR ( %SST ( YYMM 3 2 ) ) + VALUE ( % SST ( &SYSDATE 1 2 ) )

CONTROL STRUCTURES

Chapter 5

Controlling CLP Processing


A CLP is processed in a Consecutive sequence unless it is altered by Logic Control Commands Logic Control Commands can be Conditional or Unconditional Unconditional Branching alters Processing regardless of Conditions Conditional Branching alters Processing under certain conditions

Unconditional Branching
GOTO command is classic example of Unconditional Branching

GOTO command should always be used with a Label GOTO CMDLBL( label-name ) CMDLBL is a required Parameter Example of Label - Name

END : ENDPGM

Conditional Branching
IF and ELSE commands are Conditional Branching commands The IF command evaluates the condition of an Expression. If the condition is met, certain commands are executed Example : IF COND ( logical-expression ) THEN ( CL-Command )

ELSE command
The IF command may be paired with the ELSE command. ELSE command indicates what Commands to Run if the Condition is not met Example : ELSE CMD ( CL - Command )

Using DO group
The DO command triggers the Execution of a Group of Commands The commands listed after the DO command are executed until ENDDO command is reached Each DO command must have ENDDO command. ENDDO command terminates the command group

Using DO group
The commands between the DO and ENDDO are often termed as DO group DO group is executed consecutively when the DO command is triggered
CALLING PROGRAMS and PASSING PARAMETERS

Chapter 06

Processing Jobs
One of the most Important functions of CLP is to Process Jobs and CALL programs A JOB is a Unit of work submitted or Run by Users to Perform Tasks The 4 Commands that allows CALLING programs and Run jobs 1) CALL command 3) RETURN 2) TFRCTL command 4) SBMJOB

Calling Programs
The CALL command Runs a Program and Passes control to that Program Optionally, CALL command passes parameter values to the CALLED program to be processed The CALL command takes the following form :
CALL PGM ( Library / Program Name ) + PARM ( Parameter Value )

Using CALL command


Qualify an Object with the CALL command

- CALL PGM ( USRLIB / FBRCALLR )

The Library List will be used to Search the Program if an Object is not Qualified

CALL PGM ( FBRCALLR )

Transferring Control

TFRCTL command calls the Program specified in Command TFRCTL passes control to Program specified in Command TFRCTL removes the transferring Program from the Program Stack The Program stack is the Stack of Programs Active at the Time

Transferring Control
When CALL command is used the CALLING program remains Active in the Program Stack Example : TFRCTL PGM ( Library Name / + Program Name ) + PARM ( CL - Variable name )

Transferring Control
With the TFRCTL command , Control returns to the previously called program that is higher in the Program Stack when the Transferred Program Ends Examples : TFRCTL PGM ( TESTLIB / program1 ) TFRCTL PGM ( program 1 )

Returning Control
JOB The RETURN command ends the Program If the RETURN command is executed the Commands after RETURN will be Ignored RETURN command has no parameters

Submitting Jobs
SBMJOB command submits a Job to a JOB QUEUE to be Processed later as a BATCH A batch job does not require a User Intervention Batch Job runs in the Back Ground and does not tie up Users Terminal

The SYNTAX of SBMJOB


In its Simplest Form, SBMJOB CMD ( CL - Command ) The most often Used parameters in the SBMJOB command are :

CMD ( CL - Command ) JOB ( Job Name ) JOBD ( Job Description ) JOBQ ( Job Queue Name ) JOBPTY ( Job Priority )
Processing Database Files

Chapter 07

Working with Database Files


CL programs also Process and Manipulate Database Files Database Files include Physical and Logical files We can use CRTPF and CRTLF command to create a database file

List of CL Commands to Process Database Files


Create Physical File : CRTPF Create Logical File : CRTLF Override with Database File : OVRDBF Delete Override : DLTOVR Copy File : CPYF

Sort File : FMTDTA Clear Physical File Member : CLRPFM Delete File : DLTF

Create Physical File Command


CRTPF file ( lib name/physical file name) + srcfile ( lib name / src file name ) + srcmbr ( source-member-name) + rcdlen ( record length ) + share ( *yes , *no ) + lvlchk ( *yes , or *no ) + text ( text description)

Create Logical File Command


CRTLF file (lib name / physical file name)+ srcfile ( lib name/source file name)+ srcmbr ( source member name ) + share ( *no *yes ) + lvlchk ( *yes, or *no ) + aut (*change, *all, *use, or *exclude)+ text( text description)

Overriding Database Files


OVRDBF can direct the system to Process a file other than the file named in the called program OVRDBF can be used to change the attributes of the file that is being Processed

OVRDBF
OVRDBF file ( overriden - file-name) tofile ( library / file name ) frcratio ( no of records being forced as a block ) nbrrcds ( no of records being moved as a block ) share ( *yes or *no ) seqonly ( *yes or *no )

Using OVRDBF
OVRDBF is used to qualify the Library where a File is located OVRDBF file ( APMAST ) tofile ( TESTLIB / APMAST ) To override the file named in the called program, and instead to use the file specified in TOFILE parameter of OVRDBF command

Using OVRDBF
OVRDBF file ( APMAST ) tofile ( *LIBL / APWORK ) To override certain attributes of the file being Processed, and instead to use the attributes specified in the OVRDBF command SHARE ( *No ) can be overridden to SHARE ( *Yes )

Using OVRDBF
To specify the number of records being Processed as a Block to Increase the Performance When specified the Block factor, the numbers specified in FRCRATIO, NBRRCDS, and SEQONLY are normally the same

Using OVRDBF
Example : OVRDBF FILE ( APMAST ) FRCRATIO ( 2150 ) NBRRCDS ( 2150 ) SEQONLY ( *YES 2150 )

Deleting Overrides
When a File is overridden by the OVRDBF command, the Override remains effective in CLP until it is explicitly deleted DLTOVR command allows to Cancel overrides Example : DLTOVR file ( overridden-filename, *ALL, or *PRTF )

Processing DISPLAY FILES In Interactive CLPs

Chapter 08

Concept of Display File


Display file is set of Formatted Screens Display files are mainly Used for Communications between Programs and Users In Interactive mode

CL Commands for Processing Display Files


DCLF : Declare File SNDRCVF : Send and Receive File SNDF : Send File RCVF : Receive File

Declaring a File
A Display File must be declared before it is Used in a CLP Syntax of DCLF : DCLF FILE ( Library-name / File name ) RCDFMT( Record-Format-Name)

Using the DCLF command


Only one DCLF Command is allowed in a CLP The Declared File should exist before Compilation of CLP DCLF command must Precede all Other Commands except PGM and DCL commands SNDRCVF is Equivalent to EXFMT In RPG SNDRCVF command enables to send a Formatted Screen with Data to a Workstation SNDRCVF also enables to Receive Input via the Formatted Screen

Sending and Receiving Data with a Display File

Syntax of SNDRCVF
SNDRCVF DEV (*FILE or Device Name) + RCDFMT ( *FILE or Record + Format Name ) + WAIT ( *YES or *NO )

SNDRCVF
We must Declare the File before Issuing SNDRCVF command A Display File may Contain Multiple Screens or One Screen Only One Record Format can be Used in an SNDRCVF Command

Sending Data with a Display File

SNDRCVF command Function can be Divided into two Commands :

Send the File Receive File


SNDF command is Equivalent to WRITE in RPG SNDF sends a Formatted screen with Data to a Workstation

The Syntax of SNDF command


SNDF DEV ( *FILE or Device Name ) + RCDFMT ( *FILE or Record- Format Name )

Using the SEND File Command


We must Declare a Display File before Issuing SNDF command Only One Formatted Screen ( Record Format ) can be Used in a SNDF command SNDF command can only be Used for Sending a Display File Database Files can not be send with this Command

Receiving Data with Display Files


RCVF command is Equivalent to the READ opt code in RPG RCVF command receives a Formatted Screen with Input Data that are to be Processed in the Program

The Syntax of the RCVF Command


RCVF DEV ( * File or Device Name ) + RCDFMT (*File or Record Format ) + WAIT ( *YES or *NO )

Using RCVF command


We must Use the DCLF command to Declare a Display File before Issuing the RCVF command Only one Formatted Screen can be Used in an RCVF command

Working with Data Areas

Chapter 09

Concept Of Data Area


Data Area on the AS/400 is an Object with an Object type of *DTAARA Data area is used to store Data of Limited size Data stored in Data area can be changed, Displayed, and Retrieved by Individual CL commands, CLP, or RPG

Concept of Data Area ( Contd )


Data Area contains only a Single piece of Data It is not Practical to store very Complex Information Data areas are Commonly Used to store Simple and frequently Changed Data

Major Functions of Data Area


Passing Information between Programs Passing Information within Programs Supplying Reference Data that are to be processed by a Program Create Data Area : CRTDTAARA Change Data Area : CHGDTAARA Display Data Area : DSPDTAARA Retrieve Data Area : RTVDTAARA Delete Data Area : DLTDTAARA

Commands Used to Work with Data Area

Creating Data Area


Right CRTDTAARA command creates Data Area CRTDTAARA also Defines the Format of the Data Area DDS is not used for Creating Data Area

Possible Attributes of Data Area


A character string with a Maximum of 2000 characters A decimal Value with a Maximum of 15 digits to the left of Decimal Point and 9 digits to the A Logical value of 0 or 1

Syntax of CRTDTAARA
CRTDTAARA DTAARA ( Library Name / Data Area Name ) + TYPE ( *CHAR, *DEC, or *LGL) + LEN ( Length ) + VALUE ( Initial Value ) + AUT ( *change, *all,*use or *exclude ) + Text ( Description)

Changing a Data Area


CHGDTAARA can change the contents of the Data Area The new value must have the same attributes ( e.g. Type and Length ) as the attribute defined for the Data Area

Syntax Of the CHGDTAARA


CHGDTAARA DTAARA ( library name / + data area name ) VALUE ( new-value) +

Display Data Area


DSPDTAARA can be used to Display the Data and Attributes of a Data Area Syntax : DSPDTAARA DTAARA ( Library Name / data-area-name ) + OUTPUT ( * or * print ) OUTFMT ( *char or *hex )

Retrieving Data Area


RTVDTAARA command is Used to Retrieve the Contents of Data Area Syntax : RTVDTAARA DTAARA ( Library Name + / Data Area Name ) + RTNVAR ( CL Variable Name )

Differences Between Data Area and CL-Variable


A Variable is declared in CL Program It exists only during the execution of CLP When the Job ends, the Variable will be removed from the System Data area is Permanent Object It can only be Explicitly Deleted by DLTDTAARA

The Syntax of DLTDTAARA


DLTDTAARA DTAARA ( Library Name /

data - area - name )

Sending and Monitoring Messages

Chapter 10

Using Messages in CLP



CL uses User Messages to Establish Communication between Programs and Users Two Types of Messages :

System Defined Messages User Defined Messages

System Defined Messages



System Defined Messages are Predefined by the System and Stored in Messages Files System Defined Messages Include

Escape Messages Notify Messages Status Messages

User Defined Messages



User Defined Messages are Defined and Created by Users User Defined Messages Include

Predefined User Messages stored in Message Files Immediate Messages


SNDMSG : Send Message SNDBRKMSG : Send Break Message SNDUSRMSG : Send User Message SNDPGMMSG : Send Program Message MONMSG : Monitor Message

CL Commands for Sending and Monitoring Messages


Send a Message
SNDMSG command is used by a Workstation User to send a User Defined, Immediate Message to One or More Message Queues The message sent can be Informational or for Inquiry An Inquiry message requires reply from User

The Syntax of the SNDMSG command


SNDMSG MSG ( message text ) + TOUSR ( user profile name) + TOMSGQ ( message queue name) + MSGTYPE ( *INFO or *INQ ) + RPYMSGQ ( message queue name )

SNDMSG command
SNDMSG command can be used in Interactive Mode and in CL Program SNDMSG is more commonly used in Interactive Mode The Receivers of the Messages must Use DSPMSG command to display the Messages

SNDBRKMSG
The SNDBRKMSG command sends Immediate messages to Workstation Message Queues in Break Mode The Break Mode interrupts active work station Users and Displays the Message to be displayed

The Syntax of SNDBRKMSG

SNDBRKMSG MSG ( message text) + TOMSGQ ( message queue name) + MSGTYPE ( *INFO or *INQ ) + RPYMSGQ ( message queue name )

Using SNDBRKMSG command


SNDBRKMSG command can be used in Interactive Mode and in CL Program SNDBRGMSG is more commonly used in Interactive Mode

SNDUSRMSG
The SNDUSRMSG command sends a Predefined or Immediate Message to a Message Queue SNDUSRMSG can be Used only in CLPs

The Syntax of SNDUSRMSG


SNDUSRMSG MSG ( message text) + MSGID ( message id ) + MSGF ( message file name ) + MSGTYPE ( *INFO or *INQ ) + TOUSE ( User profile name ) + TOMSGQ (message queue name) + MSGRPY ( CL variable name )

SNDPGMMSG

SNDPGMMSG command is used by CLP to send a Program Message to a :

Workstation User System Operator User Message Queue

The Syntax of SNDPGMMSG


SNDPGMMSG MSG( message text) + MSGID ( message - ID ) + MSGF ( message-file-name ) + TOUSE ( user profile name ) + TOMSGQ ( message queue name ) + MSGTYPE ( *INFO or *INQ ) + RPYMSGQ ( message queue name )

Monitoring Messages
MONMSG command is used to monitor the anticipated messages in a CLP and to take actions accordingly

Main Purposes of MONMSG


To provide an Escape when an Error Message is Encountered To specify actions to be taken when certain messages occur during the execution of CLP

The syntax of MONMSG


MONMSG MSGID ( message ID ) + CMPDATA ( *none or comparison data ) + EXEC ( CL - Command )
Retrieve and Change JOB Attributes

Chapter 11

About RTVJOBA

RTVJOBA is used in a CLP to retrieve attributes of a Job and place the values in specified CL Variable RTVJOBA is valid only in CLP

******************************************************************* RPG on AS/400 -An Overview RPG -Looking Back. RPG(Report Program Generator) is an old language dating back to the 1960s. RPG is the standard applications development language for the AS/400. RPG is a System Applications Architecture language. Full Procedural Programming. It has neither a Primary File nor a Secondary File. It does not set the Last Record Indicator to ON automatically. The program has to provide the way for terminating the program.

RPG Concepts RPG Naming Conventions. First character of afield name should be an alphabet or # or @. Embedded blanks are not allowed. The valid character sets are letters A to Z, numerals 0 to 9 and special characters # and @. Maximum length of file name can be 10 characters. Maximum length of variables can be 10 characters. RPG INDICATORS An indicator is a special type of one byte flag, which sets to 1 when on and sets to 0 when off. Indicator names are always two characters long. Command key indicators are set on , whenever the corresponding command key is pressed. SETON *IN10 EVAL *IN20=1 RPG Structured Operations. Structured programming is an approach to design and coding that makes programs easy to understand, debug, and modify. A structured program is a hierarchy of modules that can have a single entry point and a single exit point. Control is passed downward through the structure without unconditional branches to higher levels of the structure.

RPG Structured Programming. Sequential Operation Sequential operation means any series of instructions that is processed one instruction after another, without transferring control to another part of the program. RPG Structured Programming. Conditional Branching - If Else Structure The If-Then-Else structure is carried out through the operation codes IFxx, ELSE, and END. C CENTR IFEQ 'Y' C CENTR OREQ 'N' C MOVE '0' *IN52 C ELSE C MOVE '1' *IN52 C END RPG Structured Programming. SELEC Structure The SELEC-WHEN-OTHER structure is carried out through the operation codes of SELEC, WHxx, and OTHER. C SELEC C X WHEQ 1 C : seq 1 C Y WHEQ 2 C X ANDLT10 C : seq 2 C OTHER C : seq 3 C ENDSL Conditional Branching Structures The CASxx operation. The GOTO operation and conditioning indicators. The CABxx operation. The EXSR operation. Do While Operation Do While structure test the condition first and then process the operations. C *IN32 DOWEQ'0' C MOVE *BLANKS STATUS C MOVE *BLANKS PRCDEX C Z-ADD0 ACDATX

C C C C

Z-ADD0 ADD 1 WRITEEMPFIL END

TFRRN RECNO 32

Do Until Operation Do Until structure process the operations first and then test the condition . C *IN50 DOUEQ'1' C READ RCEMP 50 C ADD EPHRC EPHRY C ADD EPNRC EPNRY C UPDATRCEMP C END Structured Programming The structured programming operation codes are: IFxx (If/Then) ELSE (Else Do) ENDyy (End) DO (Do) DOWxx (Do While) DOUxx (Do Until) ANDxx (And) ORxx (Or) CASxx (Conditional Invoke Subroutine) SELEC (Select a module) WHxx (When) OTHER (Otherwise). Structured Programming xx can be: GT Factor 1 is greater than factor 2. LT Factor 1 is less than factor 2. EQ Factor 1 is equal to factor 2. NE Factor 1 is not equal to factor 2. GE Factor 1 is greater than or equal to factor 2. LE Factor 1 is less than or equal to factor 2. Blanks Factor 1 is not compared to factor 2 (unconditional processing). This is valid for CASxx operation only. Structured Programming yy can be: CS End a CAS group.

_ _ _ _ _ _ _ _ _ _ _ _

DO End a DO, DO UNTIL, or DO WHILE group. IF End an IF group. SL End a SELEC group. Nested Structured Groups DO DO ENDDO IFxx SELEC WHxx ENDSL ELSE ENDIF ENDDO

Program Described Files. Records and fields are described on input/output specifications in the program that uses the file. OS/400 needs to make the connection only at Run Time. Identified by an F in position 19 of the file description specifications

Externally Described Files. An externally described file is described to the OS/400 system at the field level. The description includes information about where the data comes from, such as the database or a specific device, and a description of each field and its attributes. An externally described file is identified by an E in position 19 in the File Specification. RPG IV SPECIFICATIONS Control Specification - H in position 6. - Header specification. - To change default date format. - To change default time format. - To change default currency. - Decimal editing. File Description Specification - F in position 6. - Define all I/O Files. - Filename in position 7-16. - File type in position 17. - File designation in position 18. - File format in position 22.

- Record address type. - Device. Definition Specification - D in position 6. - Define arrays, tables. - Define data structures,data areas. - Define named constants. - Define work fields. Input Specification - I in position 6. - Define fields in program-described files. - Rename fields in externally described files. - Assign control-level indicators. Calculation Specification - C in position 6. - Arithmetic statements. - Formulas. - Decision making. - Array and table processing. - Physical file maintenance. - Display file, logical file and printer file processing. Output Specification - O in position 6. - To generate program described report format. - Page and Line spacing control. - Constants and variable field editing. RPG IV Program Compilation An RPG IV source program must be compiled to generate an object that is executed for the processing of files. CRTBNDRPG - Create Bound RPG program. CRTRPGMOD - Create RPG module. CRTPGM - Create Program. RPG IV Program Execution The RPG IV program may be executed by the following ways : Option 4 from the PDM menu. CALL pgmnm on the command line of any AS/400 display and press ENTER.

RPG- IV on AS/400
Arithmetic Functions
The traditional RPG arithmetic operations are

ADD SUB MULT DIV MVR Z-ADD Z-SUB The SEU C specification must be used to enter the syntax for RPG arithmetic operations.

The ADD operation

If factor 1 is specified, the ADD operation adds it to factor 2 and places the sum in the result field. The contents of OVRTM and REGHRS are added together and placed in TOTPAY. C OVRTM ADD REGHRS TOTPAY

The ADD operation


If factor 1 is not specified, the contents of factor 2 are added to the result field and the sum is placed in the result field. Factor 2 must be numeric. The value 1 is added to RECNO. C ADD 1 RECNO The contents of EHWRK are added to CURHRS. C ADD EHWRK CURHRS

The SUB operation


If factor 1 is specified, factor 2 is subtracted from factor 1 and the difference is placed in the result field. The contents of REGHRS are subtracted from OVRTM and placed in TOTPAY. C OVRTM SUB REGHRS TOTPAY

The SUB operation


If factor 1 is not specified, the contents of factor 2 are subtracted from the contents of the result field. The value 1 is subtracted from RECNO. C SUB 1 RECNO The contents of EHWRK are subtracted from CURHRS. C SUB EHWRK CURHRS

The MULT operation


If factor 1 is specified, factor 1 is multiplied by factor 2 and the product is placed in the result field. If factor 1 is not specified, factor 2 is multiplied by the result field and the product is placed in the result field

The MULT operation


C C C B B MULT MULT MULT E G D F X X

The DIV operation


If factor 1 is specified, the DIV operation divides factor 1 by factor 2. If factor 1 is not specified, it divides the result field by factor 2. The quotient (result) is placed in the result field. C C C DIV DIV MVR B J H Y Z

The DIV operation


Ensure that the DIV operation is processed immediately before the MVR operation.

The SQRT opcode

The SQRT operation derives the square root of the field named in factor 2. Factor 1 is never used Factor 2 holds the field from which the square root is to be computed The square root value is stored in the Result field item. C SQRT sqnbr sqrtval 6 3

The ILE RPG Opcodes


Z-ADD ( Zero and Add ) Z-SUB ( Zero and Subtract ) SETON ( Turn on the RPG indicator ) SETOF ( Turn off the RPG indicator ) MOVE ( Data Manipulation ) MOVEL( Data Manipulation ) MVR (Holds the remainder for DIV operation )

The EVAL Opcode

The EVAL operation enables to write a string of arithmetic functions in one instruction. C C C C C EVAL EVAL EVAL EVAL EVAL RESULT=FIELD1 + FIELD2+(FIELD3-FIELD4) ARR(*) = FIELD2 * FIELD3 A = 'Hello ' + CHARFIELD1 A = %TRIMR('Hello ') +%TRIML(CHARFIELD1) ISODATE = DMYDATE

The EVAL Features


The EVAL stores the result in the item specified left of the equal sign. Arithmetic operations must follow the algebraic order of operations. The type of expression must be the same as the result field- numeric or character.

Figurative Constants
Figurative Constants are implied literals that are assigned a predetermined value.

*BLANK/*BLANKS *ZERO/*ZEROS *HIVAL *LOVAL *ALLX *ON/*OFF

Subroutines
An RPG IV subroutine is a group of calculation specifications in a program that can be processed several times in that program.

EXSR ( Invoke Subroutine ) BEGSR ( Beginning of Subroutine ) ENDSR ( End of Subroutine ) CASxx (Conditionally Invoke subroutine )

Subroutines
C

EXSR ( Invoke Subroutine )


EXSR SUBRTB

BEGSR ( Beginning of Subroutine )


BEGSR

SUBRTA

ENDSR ( End of Subroutine )

CASxx (Conditionally Invoke subroutine ) C FieldA CASGE FieldB Subr01

Data Structures
Data Structure is a storage area specified in the Definition Specifications of an RPG IV program.

Data Area Data Structure File Information Data Structure Program Status Data Structure
It may be used to :

Define the same internal area multiple times using different data formats Define a data structure and its subfields in the same way a record is defined. Define multiple occurrences of a set of data. Group non-contiguous data into contiguous internal storage locations. Operate on all the subfields as a group using the name of the data structure Operate on an individual subfield using its name.

Data Areas
Data Area is a one-record permanent storage area Processed in RPG or CL program. IN - Retrieve a Data Area OUT - Write a Data Area UNLOCK - Unlock a Data Area or Release a Record The Data Area commands are : CRTDTAARA- Create Data Area. CHGDTAARA- Change Data Area. DSPDTAARA- Display Data Area. DLTDTAARA- Delete Data Area.

In Calculation Specification
C *LOCK C C C C CLR IN ADD ADD ADD OUT *DTAARA AMOUNT GROSS NET *DTAARA TOTAMT TOTGRS TOTNET

Arrays are collection of data fields or array elements with each position having the same attributes. Arrays are defined in Definition Specification. Run-time array Compile-time array Prerun-time array

Arrays

Arrays- Keywords
ALT ASCEND CTDATA DESCEND DIM FROMFILE PERRCD

TOFILE

Arrays
Run-time array
-Loaded by program while it is running.

DARC

3A DIM(12)

Arrays
Compile-time array
-Loaded when the program is created. DARC 3A DIM(12) PERRCD(5) CTDATA

**CTDATA ARC 48K16343J64044HComments can be placed here 12648A47349K346Comments can be placed here 50B125 Comments can be placed here

Arrays
Prerun-time array
-Loaded from the array file when the program begins running, before any I/O operations are processed. DARE D S 5A DIM(250) PERRCD(12) ASCEND FROMFILE(DISKIN )

Array Processing Opcodes


LOOKUP SORTA

XFOOT

MOVEA

Array Processing- LOOKUP


The LOOKUP operation causes a search to be made for a particular element of an array.

C C

SRCHWD SRCHWD

LOOKUP LOOKUP

ARY ARY(X)

26 26

Array Processing- SORTA


SORTA (Sort an array)-during program execution. Used for sorting data in array elements. Sorted in ascending or descending order

SORTA

ARRY

Array Processing- XFOOT


XFOOT-to sum the elements of an array. Sum is placed in the result field. Factor 2 contains the name of the array.

XFOOT

Character Manipulation
RPG IV character manipulation operation include:

CHECK CHECKR SCAN SUBST XLATE

CHECK
CHECK operation verifies that:

Each character in the base string is included in the comparator string. Factor1 and Factor2 must be of same attribute. The position of the non-comparator string is stored in the result field from left to right. CHECK CITYST N

ALPHA

CHECKR
CHECKR operation verifies that: C Each character in the base string is included in the comparator string(right to left). Factor1 and Factor2 must be of same attribute. The position of the non-comparator string is stored in the result field from right to left. CHECKR CITYST N

ALPHA

SCAN
SCAN string operation :

Scans the character specified in Factor2 for the characters stored in Factor1. The location of the Factor1in Factor2 is stored in the Result field. Scan operation is case sensitive. SCAN ABXYZCD HOLD 70

XYZ

SUBST
SUBST string operation : C 5 Extracts characters from Factor2 to the Result field. Factor1 indicates the number of characters to be EXTRACTED from Factor2. SUBST(P) will pad low-order positions in the result field. SUBST BASE:3 LAST 70

XLATE

XLATE translate operation :

C C

Translates a Factor2 source string according to the From and To strings formats and stores the translated Factor2 value into the Result Field. ' ':'-' MOVE XLATE '999 9999' Number Number Result 8 8

Built-in Functions

Similar to operation codes to perform operations on data. They have the percent symbol(%) as their first character. The syntax of Built-in functions is: function-name{(argument{:argument...})}

Built-in Functions %SUBST


%SUBST returns a portion of argument string C C IF %SUBST(CITY:C:1) = 'Ontario' Before the EVAL, A has the value 'abcdefghijklmno After the EVAL, A has the value 'ab****ghijklmno' EVAL %SUBST(A:3:4) = '****'

%TRIM
%TRIM functions strip the leading and/or trailing blanks in a character field value.

%TRIM - strips both leading and trailing blanks %TRIML - strips leading blanks and stores the value left-justified in the field. %TRIMR - strips trailing blanks and stores the value right-justified in the field.
C EVAL CustName = %TRIM(FirstName)+ +%TRIML(LastName)

Date and Time Operations


Date and Time operations include : To perform date and time arithmetic. To extract portions of date, time or timestamp field. Test for valid fields.

Date and Time Operations


Date and Time operations include : ADDDUR - Add Duration. SUBDUR - Subtract Duration. EXTRCT - Extract Date/Time/Timestamp. TEST - Test Date/Time/Timestamp.

ADDDUR
This operation adds the duration specified in Factor2 to a date or time and places the resulting Date ,Time or Timestamp in the result field.

C C C

LOANDATE

ADDDUR ADDDUR ADDDUR

XX:*YEARS YY:*MONTHS

DUEDATE DUEDATE

16:*Minutes answer

SUBDUR
This operation subtracts the duration specified in Factor2 from a field or constant specified in Factor1 and places the resulting Date ,Time or Timestamp in the result field. C C C LOANDATE SUBDUR SUBDUR SUBDUR XX:*YEARS ZZ:*DAYS -30:*D DUEDATE DUEDATE DUEDATE

EXTRCT
The EXTRCT operation will return one of the following to the field specified in the result field. The year, month or day part of the Date or Timestamp Field. The hours, minutes or seconds part of Time or Timestamp Field. The microseconds part of the Timestamp field.
C C EXTRCT LOGONDATE:*M LOGMONTH EXTRCT LOGONDATE:*D LOGDAY

TEST
The TEST operation code allows user to test the validity of Date , Time or Timestamp fields.
C C C C C *ISO0 *MDY0 *DMY *CMDY0 TEST (Z) TEST (D) TEST (DE) TEST (E) TEST (D) Char_Tstmp Char_Date Num_Date Datefield char_date2

Physical File Processing


Physical File maintenance include: Keyed Physical files Nonkeyed Physical files. Functions 1.Addition of records. 2.Update of existing records. 3.Logical deletion of existing records. 4.Tagging of records for deletion . 5.Reorganization.

WRITE - Create new records.


The WRITE operation writes a new record to a file. Factor2 must contain the file name or record format name. When you use the WRITE operation to add records to a DISK file, you must specify an A in position 20 of the file description specifications

WRITE

FILE1

DS1

SETLL- Set Lower Limit.


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 specified in factor 1. C ORDER SETLL ORDFIL

SETGT- Set Greater Than.

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 C C C C KEY *HIVAL SETGT FILEA READ FILEA SETGT RECDB READP RECDB

OPEN- Open file for processing.


The explicit OPEN operation opens the file named in factor 2.
FEXCEPTN FFILEX C C C C C C O E DISK USROPN F E DISK IF *in97 and not *in98 OPEN(E) EXCEPTN IF not %ERROR WRITE ERREC ENDIF ENDIF

CLOSE- Close Files.


The explicit CLOSE operation closes one or more files or devices and disconnectsthem 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.
C C CLOSE FILEB CLOSE (E) *ALL

KLIST- Define a Composite Key.


The KLIST operation is a declarative operation that gives a name to a list of KFLDs.
C C C C FILEKY KLIST KFLD KFLD KFLD DEPT SHIFT CLOCK#

KFLD- Define parts of a Key.


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

KFLDs can be global or local. A KLIST in a main procedure can have only global KFLDs associated with it. A KLIST in a subprocedure can have local and global KFLDs.

CHAIN-Random Retrieval from a File.


The CHAIN operation :

Retrieves a record from a full procedural file Sets a record identifying indicator on Places the data from the record into the input fields.
KEY C KEY CHAIN CHAIN INPUT FILEX REC1 72

Rec_No

CHAIN (N)

UPDATE- Modify Existing Record.


The UPDATE operation modifies the last locked record retrieved for processing from an update disk file or subfile.
C C C C C C C KEY KEY CHAIN KLIST KFLD KFLD IF NOT *IN72 REC1 Field1 Field2 REC1 72

UPDATE ENDIF

DELETE- Delete Record.


The DELETE operation deletes a record from a database file. The file must be anupdate file (identified by a U in position 17 of the file description specifications) The deleted record can never be retrieved.

C C C C C C C

KEY KEY

CHAIN KLIST KFLD KFLD IF

REC1

72

Field1 Field2 NOT *IN72 REC1

DELETE ENDIF

READ- Read Record.


The READ operation reads the record, currently pointed to, from a full procedural file. C DOW '1' C READ FILEA C IF %EOF C LEAVE C ENDIF C READ(N) REC1 64 C 64 LEAVE C ENDDO

READE- Read Equal Key.


The READE operation retrieves the next sequential record from a file where key field matches C C C C KEYFLD KEYFLD READE FILEA READE REC1 READE FILEA READE(N) REC1 56

READP- Read Prior Record.


The READP operation reads the prior record from a full procedural file. C READP FILEA C IF %EOF C GOTO BOF C ENDIF C C 72 C BOF READP GOTO TAG PREC1 BOF 72

READPE- Read Prior Equal.


The READPE operation retrieves the next prior sequential record from a full procedural file if the key of the record matches the search argument.

C C C

FieldA FieldB FieldC

READPE READPE READPE

FileA FileB RecA Ds1

Display File Processing.


RPG IV program is interactive when it processes one or more display files. Display Files must be defined as workstation files. EXFMT operation must be specified to process display files Record Format. FGldf1 CF E WORKSTN

EXFMT- WRITE/Then READ Format


The EXFMT operation is a combination of a WRITE followed by a READ to the same record format. EXFMT is valid only for a WORKSTN file defined as
-full procedural (F in position 18 of the file description specifications). -combined file (C in position 17 of the file description specifications).

EXFMT

SCR1

SUBFILES
Subfile is a display of multiple records of the same type. Subfile records are specified in the DDS for file. The DDS for a Subfile consists of two record formats:
Subfile record format. Subfile control record format.

To use a subfile for a display device file in an RPG program: Specify the SFILE keyword on a file description specification for the WORKSTN file. The format of the SFILE keyword is SFILE(record format name:RECNO field name). The WORKSTN file must be an externally-described file. The minimum DDS keywords required in the definition of a subfike are : SFL SFLCTL SFLSIZ SFLPAG SFLDSP

Subfile Keywords
SFL A Record Level keyword that specifies the subfile record format. SFLCTL

A Record Level Keyword that specifies the subfile control record format. SFLSIZ A Record Level control record keyword that specifies the number of records that may be loaded in the subfile. Maximum allowed records for a subfile is 9,999. SFLPAG A Record Level control record Keyword that specifies the number of records that may be displayed at the same time.

SFLDSP
A Record Level control record Keyword SFLDSP indicates when to display the subfile Displays the subfile for an output operation Conditioned by one or more indicators.

SUBFILE DDS
A R FILCTL SFLCTL(SUBFIL)

A N70 A 70 A 71 A A A A A 71 A A A A

SFLCLR SFLDSPCTL SFLDSP SFLSIZ(15) SFLPAG(15) TEXT('Subfile Control Record') OVERLAY ROLLUP(97 'Continue Search') CA01(98 'End of Program') HELP(99 'Help Key') 1 2'Customer Name Search' 3 2'Search Code'

Subfiles
Subfile applications include : Inquiry Processing. Update Processing. Adds Processing. Deletion Processing.

Inter-Program Communication Control


RPG IV operations for Inter-program communication and control are : CALL. PARM. PLIST. RETURN.

CALL
Call operations allow an RPG IV procedure To transfer control to other programs To pass control to the program specified in factor 2. C CALL 'PROGA' C PARM FieldA C PARM FieldB

PARM
PARM operation defines the parameters PARM operations can appear anywhere in calculations PARM operations immediately follow the PLIST or CALL. A CALL can have as many as 255 statements.

PARM
The result field must contain the name of a: - Field - Data structure - Array

PARM
PROG
C C C CALL PARM PARM PLIST1 *IN30 PLIST PARM PARM 'PROG1' Amount Byte 52 1

PROG1
C C C *IN27 Amount Byte 52 1

PLIST
PLIST name is a symbolic name assigned to a list of parameters. PLIST operation must be immediately followed by at least one PARM operation . Factor 1 contains the name of the parameter list or *ENTRY

The RPG Logic Cycle


Program Cycle The logic the compiler supplies is called program cycle. The compiler provided logic for programs is called cycle programming. Built-in RPG logic cycle controls Opening and closing of files. Read and write records. First page print control. Heading, detail and total-time output. Control break operations. Before reading the first record through the program,the RPG logic cycle Handles input parameters, opens files, initializes program data. Writes the records conditioned by 1P indicator. Processes all heading and detail output operations. During the last cycle ,the program sets the LR indicator,all files are closed and the program ends.

Exception/Error Handling.
RPG categorizes Exceptions/Errors into two classes : File Exception/Errors Program Exception/Errors File Exception/Errors can be caused due to : Undefined record type. I/O operation to a closed file . Device error. Array load sequence error. File Exception/Errors can be handled in following ways : Operation code extender E can be specified. Indicator can be specified in position 73 and 74. File information Data structure. File Exception/Error subroutine can be specified.

File Exception/Error.

File Information Data Structure.


A file information data structure (INFDS) can be defined for each file to make file exception/error and file feedback information available to the program. FMYFILE IF E DISK INFDS(FILEFBK)
* File name * File open * File at eof * Status code DFILEFBK DS D FILE *FILE D OPEN_IND 9 9N D EOF_IND 10 10N D STATUS *STATUS D OPCODE *OPCODE

File Exception/Error Subroutine.


A file exception/error subroutine (INFSR) receives control when an exception/error occurs on an implicit file operation or on an explicit file operation.

Program Exception/Error.
Program exception/errors are runtime errors occurs when program encountersDivision by zero. SQRT of a negative number. Invalid array index. Error on a CALL. Start position or length out of range for a string operation. Program exception/errors can be handled by Program Status Data Structure Program Exception/Error Subroutine

Program Exception/Error.

Program Status Data Structure.


A program status data structure (PSDS) can be defined to make program exception/error information available to an RPG IV program. DMYPSDS SDS D PROC_NAME D PGM_STATUS D PRV_STATUS D LINE_NUM D ROUTINE D PARMS *PROC *STATUS 16 20S 0 21 28 *ROUTINE *PARMS

Program Exception/Error Subroutine.


To handle a program error or exception,write a program error subroutine (*PSSR). When a program error occurs: The program status data structure is updated. The error is handled and control is transferred to the *PSSR .

Program Exception/Error Subroutine.


To add a *PSSR error subroutine to program, do the following steps: 1. Optionally identify the program status data structure (PSDS) by specifying an S in position 23 of the definition specification. 2. Enter a BEGSR operation with a Factor 1 entry of *PSSR.

Program Exception/Error Subroutine.


3. Identify a return point, if any, and code it on the ENDSR operation in the subroutine. 4. Code the rest of the program error subroutine. 5. Any of the ILE RPG compiler operations can be used in the program error subroutine.

6. ENDSR operation must be the last specification for the program error subroutine.

Program Exception/Error Subroutine.


D Psds D Loc D Err D Parms D Name SDS *ROUTINE *STATUS *PARMS *PROC

Program Exception/Error Subroutine.


C *PSSR

BEGSR IF Err = 102 ADD 1 Divisor MOVE '*GETIN' ReturnPt ELSE MOVE ENDIF ENDSR '*CANCL' ReturnPt ReturnPt

C C C C C C C

DB2/400 ADVANCED FEATURES


TRIGGER PROGRAMS DISTRIBUTED DATABASE

Trigger
A condition that causes some procedure to be executed. Trigger program is a program that DB2/400 calls when the application program attempts to change a database record DB2/400 automatically calls the trigger program you specify for the associated file and condition( trigger event and time)

Six trigger conditions for a physical file


Before insert Before update Before delete After insert After update After delete

Implementing triggers
This is a two-step process 1. Code a trigger program 2. Associate the program with one or (what to do when the action happens) more trigger conditions for a file or even for multiple files

ADDPFTRG associates a trigger program to a file. RMVPFTRG removes it

Coding a trigger Program


You can code in RPG/IV,COBOL/400 or in any other AS/400 HLLs. Trigger program fills the trigger buffer Layout of the trigger buffer

Fixed part
images.

-- Physical file name, library, member, Time(before/after)

Trigger event (insert,update,delete)

Variable part

-- Images of the record before and after changes, null field maps for the

Check for the before and after images according to the condition and write the exception

Distributed Database
The most important distributed database facilities are Distributed Data Management (DDM) Distributed Relational Database Architecture (DRDA) Open Database Connectivity (ODBC)

DDM
Way to define a DB2/400 file in one AS/400 and access it from another AS/400. Steps involved are: Create a database file on the target system Create a DDM file in the source (local) system using CRTDDMF command Configure a communication link between the two systems. Open the DDM file from an application on the source system.

DRDA
It is the standard for interoperation among the DB2 family of DBMS. To access the data from a remote database On AS/400, we use SQL/400 to use DRDA Before executing a statement on a remote system, we use connect statement to connect to that system. ADDRDBDIRE (Add Relational Database directory entry) adds an entry of the remote database in the local systems directory before use.

ODBC
Standard developed by Microsoft for access to relational databases from Windows-based applications Unlike embedded SQL, this uses function calls to access data. ODBC driver manager (a windows DLL) makes the user to choose one database at runtime. All SQL Insert, Update, and Delete operations, as well as to open cursors and fetch operations will be available to the user. ODBC also supports dynamic SQL statements, calls to stored procedures, and other database functions. Anything is possible with ODBC, like getting a physical files data in an Excel sheet or load a word document with the data from a table.

Data Area Handling


AS3040

Definition of Data Area


Data area is the Single Field File with just Single record (?) A data area is an AS/400 object (*DTAARA) which can store a small amount of information. It is used to store simple and frequently changing information/data.

DATA AREA

A data area can be changed, displayed and retrieved by CL commands, CL programs or HLL programs like RPG/400.

Uses of DATA AREA


Passing information between programs Passing information within a program Supplying reference data that are processed by programs e.g. current interest rates which can change from day to day or stock rates which can change from time to time.

Processing data area(s) using CL commands


Data areas can be processed using CL commands These commands can be executed from the command line or from any CL programs

Creating a data area


(CTRDTAARA)
Data areas are created using the CL command CRTDTAARA(create data area) e.g.. CRTDTAARA DTAARA(libraryname/data-area name) TYPE(data-area-type) LEN(data-area length decimalpositions) VALUE(initial value) TEXT(description) DTAARA parameter specifies the name of the data area. TYPE parameter specifies the type of the data area. Valid types are *CHAR - for character type *LGL - for logical type and *DEC - for decimal type

LEN parameter specifies the length of the data area. Max.length of decimal is 15 positions before the decimal point and 9 positions after it. Max. length of character type is 2000. VALUE is a optional parameter is used to specify the initial value to be present in the data area.

Displaying a data area


(DSPDTAARA) Contents of data area can be printed or displayed using DSPDTAARA(display data area ) command e.g. DSPDTAARA DTAARA(library-name/ data-area-name) OUTPUT(display-or-print) OUTFMT(output-format) OUTPUT parameter can either contain a *, if you want to display the data area on the screen(default) or *PRINT if you want to print the output. OUTFMT parameter lets you specify the format of the output , either the default *CHAR format or *HEX format Retrieving the contents of a data area(RTVDTAARA) The contents of the data area or a portion of *char data area can be retrieved into a CL variable using the RTVDTAARA command. e.g..RTVDTAARA DTAARA(library-name data-area-name (substring-start-position substring-length)) RTNVAR(&CL-variable name)

Retrieving the contents of a data area(Cont...)


DTAARA parameter specifies the name of the data area whose value is to be retrieved. RTNVAR parameter specifies the CL variable name into which the contents of the data area is to be retrieved. The default of the copy is *ALL unless you specify the length and starting position of the data area content to be copied Changing the contents of a data area(CHGDTAARA) The entire contents of the entire data area or a portion of the *CHAR data area can be changed by using CHGDTAARA(change data area command)

e.g..CHGDTAARA DTAARA(library-name data-area-name (substring-start-position substring-length)) VALUE(new value) Deleting a data area (DLTDTAARA) A data area can be deleted using the DLTDTAARA(delete data area) command. e.g.. DLTDTAARA DTAARA(library-name/ data-area-name)

The Local Data Area


Automatically provided by AS/400 for each job in the system. Not a permanent Object. Created when a job is started and disappears when the job ends. RTVDTAARA,CHGDTAARA and DSPDTAARA can be used on Local data area using the DTAARA(*LDA).

Explicit creation/deletion of LDA is not possible When using SBMJOB the submitting jobs *LDA is copied to the submitted jobs LDA. After the job is submitted , its *LDA exists separately from that of the submitting job . *LDA can be used to pass values from one program to another.

ILE CONCEPTS Integrated Language Environment Why ILE?


Creating an ILE Program.
Modules. Binding.

Service Programs. Binding Directories. Program Activation. Improved Performance.


Call intensive applications. Promote modular Programming. Mixed language applications.

Efficient Use of Runtime Storage.


Runs entire application in single Runtime Environment.

Consistent Error and Exception Handling. Easier migration Source-Level Debugging Improved System Openness.
Provides System interfaces by means of APIs. For eg. CEEHDLR: Conditioner handlers, CEEFRST: Frees storage etc.

Application Component Replacement.


Lets you replace one component of the application without recompiling all programs that use that one component.

ILE Program Types


Unbound programs Bound programs Service programs


ILE uses new call operation.

Creating an ILE Program

CALLB - CALL Bound. Used for calling procedures that are bound into the same *PGM object as the calling Module

Modules.
Use CRTxxxMOD command.
Creates non-executable module objects, object type *MODULE.

Use CRTBNDxxx command, if there is only one module that constitutes your entire application. Option - 14.

Modules
Modules are the building blocks of ILE programs. It is non-executable code and can consist of one function(procedure) or more. For eg. ILE C source module can contain any number of functions. But ILE RPG permits a single function per module. They also contains information required by the system to generate an executable program

Data Sharing in Modules.


ILE lets application programs share Data objects through these modules. Define data in one module and Declare data in another. Use EXPORT( Define) and IMPORT(Declare) keywords on D-SPEC

Creating ILE Program


Binding
Use CRTPGM object to create an executable program object (*PGM). List all the modules that comprise the application program When the CRTPGM command is issued the resulting bind step resolves all references and copies all the statically bound modules to the final executable objects.

Binding

Binding is a mechanism for linking multiple program components (modules) to produce a single application. Binding also identifies the main, or starting, entry point for the application. CRTPGM command has a parameter (ENTMOD) that identifies that point as Program Entry Procedure(PEP).

Types of binding.
Dynamic Binding Static binding.

Dynamic binding supplies a pointer to each of those modules. System resolves this pointer to a physical address during run time. In static binding all resolution happens at compilation time. Static binding is done in two ways.
Bind by copy. The system physically copies all modules into the application that will use them. Bind by reference. The system statically binds to a service program, that has an export needed.

Dynamic bind is good solution


If the modules are large and infrequently called. If a single module is used in many applications.

Static bound is good solution if


If the size of modules is less and frequently called. A module is not being used in many applications.

Service Programs
Service programs provides a collection of runnable procedures and data items that other ILE programs or service programs can easily and directly access by means of a call.They cant be called from the command line. Why Service programs ?
Gives individual protected interfaces for specific modules. Allow multiple program entry points. Can reduce program size.

ILE Binder Language



Export parameter specifies the functions, procedures and data items to be externalized. To specify the same ILE Binder Language is used. The commands used : STRPGMEXP, EXPORT and ENDPGMEXP.

Binding Directories
These objects contain the names of modules and service programs that are needed during creation of a program/Service Program. The system searches the binding directory for the objects needed at bind time, you dont have to specify the list of all modules while program creation. The binding directory facility gives the binder the physical address of the required procedure or data item. Use CRTBNDDIR to create binding directory.

Program Activation
Before executing an ILE application, the system determines all the resources that will be necessary to execute that program. These resources are Dynamic, Static and Automatic storage. Extra storage for execution. Temporary data management resources. Exception handlers Ending procedures for program termination. Then, only for the purpose and duration of this programs execution the system creates an environment that allocates all these resources. The environment within which an ILE program is executed is called activation group.

Because a job can have its own activation group, the job can manage resources without worrying about conflicts with other jobs executing in different activation groups. Unrelated applications such as packages from different vendors have their own environment in the same job and thus avoid resource conflicts. A program is activated once per activation group. If the program is called again, the system will not reactivate it. An activated programs remains activated until the system destroys the activation group. Note: For any ILE program activated for the first time within an activation group, the system checks for binding to any service programs. If the program being activated has calls to service programs, these service programs are activated as part of the same call. The process is repeated for each service program in the application program until all necessary service programs are activated

Modeling is the collective task of figuring out and documenting the business requirements, including data and processes that use data. Logical Data modeling concentrates on the data requirements of the organization. Physical Database design is the task of deciding how to implement a system for a particular data model.

DATA MODELING & DATABASE DESIGN. Modeling and Design

Specifications in the data model document includes


Objects Events Relationship between objects and events Details about objects, events and relationships Business rules or policies

Logical Data Modeling

Physical Database Design


Physical database design is the process that weighs the alternative implementation possibilities and carefully lays out exactly how file and other elements of the system will be set up.

Relational Concepts
The relational model is good because it has an intuitive representation thats effective for communicating with the end users. It helps in the smooth flow from data modeling to database design to implementation.

JOURNAL MANAGEMENT & COMMITMENT CONTROL Why Journal Management?


Used to recover critical data in AS/400 files during a hardware or software malfunction. It automatically creates a separate copy of file changes. When used with save/restore function gives you capability for restoring the database files up to the very minute of a failure that damaged the file.

Basic Journaling
The changes to the file are recorded in the same manner and sequence by the journal. The changes are recorded as Journal entry into an object known as Journal receiver, which is the actual repository. The entry has system generated information, including a journal code and entry type which identifies it, along with the copy of the changed data. The copy of the record after it has been changed is known as after image. If a failure occurs the journal entry and the file backup are synchronized to get the desired recovery

Setting up Journaling
The files to be journaled have to be identified depending on the criticality, size and volatility or their relation to other files with these characteristics. The grouping of the files into one or many journal depends on the application.A single journal should be used for files that are closely related to each other. Establish for each file whether to keep after images or both before and after images.(When a file is under use in commitment control the system defaults to the second case.) Decide whether to go for single or dual journal receivers depending on the disk space and data criticality. Decide on the user ASP unit where the journal receiver is to be placed.

Journaling process
Create the journal and the journal receivers in the same library as the physical file using them to simplify the backup/restoration process. Create receivers using CRTJRNRCV. Create journals using CRTJRN. Start journaling using STRJRNPF. The file should be saved immediately after beginning journaling and also after adding a member to the file. The journal and journal receivers should be saved daily. The journal receivers should be changed daily.

Recovery process
Recovery of an individual file involve restoring the most recently saved version of the file, then using APYJRNCHG command.

Commitment Control
AS/400 facility that protects the integrity of the database and helps the recovery from abnormal system terminations. Facilitates the roll back of the file updates that has been performed as part of incomplete transaction, it is carried out before the affected records can be accessed. With CC no update can be wiped out by another jobs rollback operation because the second update is blocked until the first job releases its record locks at the end of the transaction. Identify which files to be placed under CC. Specify in the CL and HLL those files. Add commit and rollback statements in your program to define the boundaries for both successful and unsuccessful transactions. Journal physical files accessed under CC. Start CC environment in a job before opening any files under CC. End the CC environment when it is no longer needed in a job

OPEN QUERY FILE COMMAND

OPNQRYF

Open Query File


Most powerful CL command Creates temporary access path to a file This access path can be used only by the job which executes the OPNQRYF command A HLL can be used to access the records from the derived file (file containing a subset of records of original file)

Uses of Open Query File


Select a subset of available records Order records by one or more fields in the record Join records from different files into one access path Group records together Calculate new fields that do not exist in the physical file

Example of OPNQRYF
OPNQRYF FILE (libname/filename membername OPTION (open-option) FORMAT(libname/db-filename QRYSLT(query-selection) order) record format name) recordformat name) KEYFLD(file/field collating

FILE parameter
record The FILE parameter identifies the database file(s) to be processed by the OPNQRYF statement. You can specify the member within the file You can specify a record format name(e.g.. when there is join of files)

OPTION parameter
The OPTION parameter is used to specify the type of processing to be done with the The options are input,output,update,delete and *ALL. Specify one or a combination of the above options Default is that the file is opened as input file

FORMAT parameter
The FORMAT parameter indicates the record format the program will use Usually the same record format specified in the FILE parameter is used by using default FORMAT(*FILE) . Specification of different file and format is also possible and is a must when processing multiple files

QRYSLT parameter
The QRYSLT parm tells the program which records to select from a file. The default is *ALL(select all records) You can enter an expression upto 2000 character long in the QRYSLT parameter e.g. QRYSLT(custno *ge 1256 *and custcode *eq P) Use of string and arithmetic functions possible

KEYFLD parameter
Specifies an order in which the OPNQRYF presents records One or more key fields can be included

Key field(s) can be ordered as ascending(default) or descending No. of unique key fields can be specified Records can be arranged in absolute value(*ABSVAL) or by their signed value(default)

JFLD parameter
Used to create a dynamic joining between two or more files Specify the join operator between fields Join can be done with/without default values Join file order can be specified. Also grouping field name(s) can be specified Grouping of records can also be done by the GRPSLT keyword GRPSLT is similar to the QRYSLT keyword You can specify the selection of grouped records by this keyword. The GRPSLT selects records after combination but QRYSLT selects records before combination

MAPFLD parameter
Allows you to derive new fields using fields from the physical file Specify the mapped field and the definition of the field Specify the length and type of the mapped field.

OPNID Parameters
Specifies the identifier used to open the query file so that it can be used in the close file or position database File command when the file is closed. Should be different from previously opened database files or query files which are not closed Default is the name of the file(*FILE) You can also specify the OPNID identifier

Other Parameters
SEQONLY - Specifies whether sequential processing is used for the file OPNSCOPE - Specifies the scope of the open operation. Values allowed are *DFTACTGRP(default activation group),ACTGRP(all shared open from same activation group) and *JOB(scope is the job in which open occurs DUPKEYCHK - Specifies whether duplicate key checking should be done on I/O operations for the file opened ALWCPYDTA - Specifies whether system is allowed to copy data from the files specified. Default is *YES .Other options are *NO and *OPTIMIZE (Here system uses a sort routine to order the records).

CPYFRMQRYF
Copy from Query File Command

CPYFRMQRYF
OPNQRYF opens a data path to a file, selecting and sorting records. This path should be processed in a HLL Direct processing of an OPNQRYF data path is not possible The records can be processed only if a copy of the records in the data path is used. This processing is done by CPYFRMQRYF

E.g.. of CPYFRMQRYF
CPYFRMQRYF TOFILE(lib name/file name) MBROPT(replace-option) NBRRCDS(number of records) FROMOPNID(open-id-name) TOMBR(member name) CRTFILE(create-file-option)

CPYFRMQRYF parameters

FROMOPNID - This is usually the file name or the OPNID parameter from the QRYSLT expression TOFILE and TOMBR - Copy is made to the qualified file name and member specified in the TOFILE and TOMBR parameters MBROPT - The various member options are 1) *none - if the TOFILE does not exist 2) *add - to add to the existing TOFILE 3)*replace - to replace existing records in a TOFILE CRTFILE - Specifies whether the file mentioned in TOFILE needs to be created or not. NBRRCDS - Specifies the no. of records to be copied. *END specifies that all the records can be copied or a limit can be set by specifying the no. of records that need to be copied

Processing jobs under Work Management


The Work Management Concept
AS/400 work management is the core of the AS/400 operating system(OS/400). It provides the functions to control system operation and job processing on the system. All jobs that run on the system are controlled and managed by the Work Management. AS/400 controls both interactive and batch jobs, as well as spooling activities. AS3040

The Work Management Structure


AS/400 Work Management has three major levels in its structure 1) System 2) Subsystems and 3) Job Entries

System
The AS/400 system as a whole is defined by system values and network attributes which should be configured when the system is first set up. Examples of system values are system date, time and Object authority. Examples of network attributes are system name, local network ID and network server name. Both system values and network attributes can be retrieved and changed using CL commands.

System (Cont)
Retrieve System Value(RTVSYSVAL) command is used to retrieve a system value. RTNSYSVAL SYSVAL(system-value-name) RTNVAR(CL-variable-name) Change System Value(CHGSYSVAL) command is used to change a system value. CHGSYSVAL SYSVAL(system-value-name) VALUE(new-value)

System (Cont)
Retrieve Network Attributes (RTNNETA) command system. RTNNETA SYSNAME(CL-variable-name) NETSERVER(CL-variable-name) The retrieved values are placed in CL variables is used to retrieve the network attributes of the LCDNETID(CL-variable-name)

System (Cont)
Change Network Attributes (CHGNETA) command is used to change the network attributes of the system CHGNETA SYSNAME(system-name) LCDNETID(local-network-id) NETSERVER(network ID)

Subsystems
Subsystems provide the capability of having many operating environments as necessary to meet the needs. All jobs must run in job queues under Subsystems. Subsystems can be classified into two:1) IBM-supplied subsystems 2) user-created subsystems

IBM-supplied Subsystems
The AS/400 is shipped with several IBM-supplied Subsystems. Some of them are given below. QBASE - default subsystem that allows users to run all the jobs when the system is first installed. Since it is inefficient to run all the jobs in one system, as soon as the system is installed you should change the subsystem that run the jobs. QCTL - subsystem that starts and ends other subsystems such as QBATCH, QSPL etc. and also controls the fns. of other subsystems.

IBM-supplied Subsystems
QBATCH - Subsystem which contains the job queues that allow batch jobs to be submitted and run. It arranges and manages the batch entries, job priorities and running of the active jobs. QINTER - Subsystem which contain workstation entries that allow interactive jobs to run simultaneously in the subsystem. QSPL - Subsystem which has spooled job queue entries for spooled jobs.

IBM-supplied Subsystems
QCMN - Subsystem which has communication entries for all communication jobs that are run.

User-created Subsystems
Users can create and define their own subsystems to suit their own needs. Users can create subsystems such as QPGMR( to compile programs), QBATCH2( the second batch subsystem) etc..

Job Entries
Job entries are depositories where jobs actually run. There are 4 types of job entries. Job Queue Entries -- Job queues that are normally defined and created in the subsystem that run batch jobs. (e.g.. QBATCH) Work Station Entries -- Entries that are defined in the subsystems that run interactive jobs. (e.g.. QINTER)

Job Entries
Spooled Job Entries -- Job queues that are defined in the subsystem that run spooled job (e.g.. QSYS) Communication Entries -- Normally defined in QCMN subsystem. They contain communication protocols and allow communication jobs to run.

Jobs
A job is a set of tasks performed on the computer system. Any number of functions can be performed within a job. Jobs can be requested by a single CL command, a series of CL commands , a single program or a series of programs. Depending on their nature and type, jobs are classified into the 5 categories.

Batch Jobs
Batch Jobs are jobs that are run in the batch mode. It usually requires a lot of I/O and takes a long time to run. The SBMJOB command is used to submit a batch job. After a batch job is submitted, it is placed in a job queue specified in the command to be stared by the subsystem(e.g.. QBATCH) . The jobs are processed in order of priority and sequence.

Interactive Jobs
Interactive jobs involve online, real-time processing between the users and the system. To start a interactive job a CALL command should be issued from the command line. An Interactive job runs in the foreground and ties up the terminal until the job ends. Interactive jobs run in subsystem such as QINTER Multiple interactive jobs can be run in an interactive system.

Auto start Jobs


Autostart jobs are started automatically when a subsystem is started. The Add Autostart Job Entry (ADDAJE) is used to specify the Autostart job to be started when the subsystem starts.

Spooled Jobs
Spool is a system function by which jobs are placed in a depository area where they wait to be processed or printed.

Spooled jobs include input spooling and output spooling. Input Spooling -- Involves taking spooled jobs from an input device, arranging them in order of priority and sequence and placing them in the job queue.

Spooled Jobs
Output Spooling -- This involves sending the output of the jobs into spooled files rather then directly to printer. The spool files are printed if printer and Printer Writer are set active. WRKSPLF(Work Spool File) command is used to work with the spooled files.

Communication Jobs
These run in communication entries in QCMN subsystem When a network connection is established between local and remote system, you must define the Logical Units(LU) and communication entries for both systems. These jobs are started when the remote system requests the subsystem to initialize a program and allocate resources. These requests are then send to LU that allocates devices for communication jobs.

Major Subsystem and Job Commands Create Subsystem Description


The CRTSBSD is used to create a subsystem description that defines the attributes of the subsystem being created. CRTSBCD SBCD(system-description-name) POOLS(pool-identifier pool-definition) MAXJOBS(maximum-subsystem-jobs) SGNDSPF(sign-on- display-file-name) SYSLIBLE(library-name) AUT(*change, *all, *use or *exclude) TEXT(text description)

Create Subsystem Description


The following command creates a subsystem called QPROD which contains 2 pool definitions: the pool1 has 200K storage and active level of 3 and pool2 shares the base system pool. Up to 6 jobs can run at the same time. CRTSBCD SBCD(QPROD) POOLS((1 200 3) ( 2 *BASE)) MAXJOBS(6) TEXT(Production Subsystem)

Start Subsystem (STRSBS)


The STRSBS command is used to start a subsystem specified in the SBCD parameter. STRSBS SBCD(system-description-name) e.g.. STRSBCD SBCD(QBATCH2)
This will start the subsystem QBATCH2.

End Subsystem (ENDSBS)


The ENDSBS command is used to end a subsystem specified in the SBCD parameter. ENDSBS SBCD(system-description-name) OPTION(*CNTRLD or *IMMED) DELAY(delay-time) Option *CNTRLD specifies that the subsystem is ended in a controlled manner i.e.. The subsystem will end after all the jobs in the system finishes. Option *IMMED ends the subsystem immediately All jobs in the subsystem ends abnormally.

Add Job Queue Entry (ADDJOBQE)


The ADDJOBQE command allows you to add a job queue entry to a subsystem. ADDJOBQE SBCD(lib/system-description-name) JOBQ(lib/job-queue-name) MAXACT(maximum-active-jobs)

Submit Job (SBMJOB)


The SBMJOB command allows you to submit a job to a batch job queue. SBMJOB JOB(job-name) JOBD (job-descriptionname) JOBQ(job-queue-name) JOBPTY(job-priority CMD(CL-command-to-run) HOLD(*yes or *no) DATE(*SYSVAL or job-date) SWS(*JOBD or job-switch-settings)

Work with Active Jobs (WRKACTJOB)


WRKACTJOB command allows you to obtain the current status and other information about active jobs in the system. WRKACTJOB OUTPUT(* or print) SBS(*ALL or subsystem-name)

Work with Subsystem Jobs (WRKSBSJOB)


WRKSBSJOB command allows you to obtain the current status and other information regarding the jobs that are running in a specific subsystem. WRKSBSJOB SBS( subsystem-name) OUTPUT(* or print)

Work with Spooled Files (WRKSPLF)


WRKSPLF allows you to work with the spooled files created by the user. WRKSPLF OUTPUT(* or print)

Work with Output Queue (WRKOUTQ)


WRKOUTQ command is used to work with the output queue specified in the OUTQ parameter. WRKOUTQ OUTQ(output-queue-name) OUTPUT(* or print)

The Job Description


A job description is a object with the object type *JOBD. It contains a set of parameters that defines how a job should be processed. JOBQ -- Specifies the job queue in which the job should be placed when it is submitted. OUTQ -- Specifies the output queue where the output of the job is to be placed.

The Job Description


JOBPTY -- It specifies the job priority of the job. INLLIBL -- It lists the libraries to be used as the user portion of the library list for the job. The library list is then used by the job to locate the objects to be processed for the job.

Potrebbero piacerti anche