Professional Documents
Culture Documents
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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.
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.
Rebuild Delay
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.
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.
In a data model, a primary key of the parent entity becomes the foreign key in the referenced or dependant entity. Order
Integrated model is the schema or conceptual schema. Integrating multiple views involves : Identifying columns. Resolving domain. Synthesizing the schemas 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.
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
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
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
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.
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.
CLP Structure
Built-in Functions Program Control Commands The ENDPGM Command Comment Lines Labels in CPP
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
Built-In Functions
Predefined Functions that allow CLP to perform special functions like
%SWITCH %SUBSTRING
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 Name of Variable Its Type Its Length Its 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
Arithmetic operators are used for performing calculations in Arithmetic expressions Arithmetic expressions are often used
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
CL BUILT-IN FUNCTIONS
Chapter 04
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
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 )
% 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
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 )
The Library List will be used to Search the Program if an Object is not Qualified
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
CMD ( CL - Command ) JOB ( Job Name ) JOBD ( Job Description ) JOBQ ( Job Queue Name ) JOBPTY ( Job Priority )
Processing Database Files
Chapter 07
Sort File : FMTDTA Clear Physical File Member : CLRPFM Delete File : DLTF
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 )
Chapter 08
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)
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
Chapter 09
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)
Chapter 10
CL uses User Messages to Establish Communication between Programs and Users Two Types of Messages :
System Defined Messages are Predefined by the System and Stored in Messages Files System Defined Messages Include
User Defined Messages are Defined and Created by Users User Defined Messages Include
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
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
SNDBRKMSG MSG ( message text) + TOMSGQ ( message queue name) + MSGTYPE ( *INFO or *INQ ) + RPYMSGQ ( message queue name )
SNDUSRMSG
The SNDUSRMSG command sends a Predefined or Immediate Message to a Message Queue SNDUSRMSG can be Used only in CLPs
SNDPGMMSG
Monitoring Messages
MONMSG command is used to monitor the anticipated messages in a CLP and to take actions accordingly
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
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.
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 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 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
Figurative Constants
Figurative Constants are implied literals that are assigned a predetermined value.
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
SUBRTA
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 )
XFOOT
MOVEA
C C
SRCHWD SRCHWD
LOOKUP LOOKUP
ARY ARY(X)
26 26
SORTA
ARRY
XFOOT
Character Manipulation
RPG IV character manipulation operation include:
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
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...})}
%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)
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
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
WRITE
FILE1
DS1
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
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
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.
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 ENDIF
C C C C C C C
KEY KEY
REC1
72
DELETE ENDIF
C C C
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.
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
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.
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.
6. ENDSR operation must be the last specification for the program error subroutine.
BEGSR IF Err = 102 ADD 1 Divisor MOVE '*GETIN' ReturnPt ELSE MOVE ENDIF ENDSR '*CANCL' ReturnPt ReturnPt
C C C C C C C
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)
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
Fixed part
images.
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
A data area can be changed, displayed and retrieved by CL commands, CL programs or HLL programs like RPG/400.
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.
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)
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.
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.
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
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.
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.
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.
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.
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
OPNQRYF
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
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.
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.