Natural PDF
Natural PDF
Programming Guide
February 2010
This document applies to Natural Version 4.2.6 for Mainframes (Update). Specifications contained herein are subject to change and these changes will be reported in subsequent release notes or new editions. Copyright 1979-2010 Software AG, Darmstadt, Germany and/or Software AG USA, Inc., Reston, VA, United States of America, and/or their licensors. The name Software AG, webMethods and all Software AG product names are either trademarks or registered trademarks of Software AG and/or Software AG USA, Inc. and/or their licensors. Other company and product names mentioned herein may be trademarks of their respective owners. Use of this software is subject to adherence to Software AG's licensing conditions and terms. These terms are part of the product documentation, located at http://documentation.softwareag.com/legal/ and/or in the root installation directory of the licensed product(s). This software may include portions of third-party products. For third-party copyright notices and license terms, please refer to "License Texts, Copyright Notices and Disclaimers of Third-Party Products". This document is part of the product documentation, located at http://documentation.softwareag.com/legal/ and/or in the root installation directory of the licensed product(s).
Table of Contents
1 Programming Guide ....................................................................................................... 1 2 Natural Programming Modes ......................................................................................... 3 Purpose of Programming Modes ............................................................................... 4 Setting/Changing the Programming Mode ............................................................... 5 Functional Differences ............................................................................................... 5 3 Object Types .................................................................................................................. 11 4 Using Natural Programming Objects ............................................................................ 13 Types of Natural Programming Objects .................................................................. 14 Creating and Maintaining Programming Objects .................................................... 14 5 Data Areas ..................................................................................................................... 15 Use of Data Areas ..................................................................................................... 16 Local Data Area ........................................................................................................ 16 Global Data Area ...................................................................................................... 18 Parameter Data Area ................................................................................................ 26 6 Programs, Subprograms and Subroutines .................................................................... 31 A Modular Application Structure ............................................................................ 32 Multiple Levels of Invoked Objects ......................................................................... 32 Program .................................................................................................................... 34 Subroutine ................................................................................................................ 37 Subprogram .............................................................................................................. 42 Processing Flow when Invoking a Routine .............................................................. 44 7 Processing a Rich GUI Page - Adapter .......................................................................... 47 8 Maps .............................................................................................................................. 49 Benefits of Using Maps ............................................................................................ 50 Types of Maps .......................................................................................................... 50 Creating Maps .......................................................................................................... 51 Starting/Stopping Map Processing ........................................................................... 51 9 Helproutines .................................................................................................................. 53 Invoking Help .......................................................................................................... 54 Specifying Helproutines ........................................................................................... 54 Programming Considerations for Helproutines ...................................................... 55 Passing Parameters to Helproutines ........................................................................ 55 Equal Sign Option .................................................................................................... 56 Array Indices ............................................................................................................ 57 Help as a Window .................................................................................................... 57 10 Multiple Use of Source Code - Copycode ................................................................... 59 Use of Copycode ...................................................................................................... 60 Processing of Copycode ........................................................................................... 60 11 Documenting Natural Objects - Text ........................................................................... 61 Use of Text Objects ................................................................................................... 62 Writing Text .............................................................................................................. 62 12 Creating Component Based Applications - Class ....................................................... 63 13 Using Non-Natural Files - Resource ............................................................................ 65
iii
Programming Guide What are Resources? ................................................................................................ 66 Use of Resources ...................................................................................................... 66 API for Processing Resources ................................................................................... 67 14 Defining Fields ............................................................................................................. 69 15 Use and Structure of DEFINE DATA Statement ......................................................... 71 Field Definitions in DEFINE DATA Statement ........................................................ 72 Defining Fields within a DEFINE DATA Statement ................................................ 72 Defining Fields in a Separate Data Area .................................................................. 73 Structuring a DEFINE DATA Statement Using Level Numbers ............................. 73 Storage Alignment ................................................................................................... 76 16 User-Defined Variables ................................................................................................ 77 Definition of Variables .............................................................................................. 78 Referencing of Database Fields Using (r) Notation ................................................. 79 Renumbering of Source-Code Line Number References ......................................... 80 Format and Length of User-Defined Variables ........................................................ 81 Special Formats ........................................................................................................ 83 Index Notation ......................................................................................................... 85 Referencing a Database Array .................................................................................. 88 Referencing the Internal Count for a Database Array (C* Notation) ...................... 95 Qualifying Data Structures ...................................................................................... 99 Examples of User-Defined Variables ...................................................................... 100 17 Introduction to Dynamic Variables and Fields .......................................................... 101 Purpose of Dynamic Variables ............................................................................... 102 Definition of Dynamic Variables ............................................................................ 102 Value Space Currently Used for a Dynamic Variable ............................................ 103 Allocating/Freeing Memory Space for a Dynamic Variable .................................. 103 18 Using Dynamic and Large Variables ......................................................................... 107 General Remarks .................................................................................................... 108 Assignments with Dynamic Variables ................................................................... 109 Initialization of Dynamic Variables ........................................................................ 111 String Manipulation with Dynamic Alphanumeric Variables ............................... 111 Logical Condition Criterion (LCC) with Dynamic Variables ................................. 113 AT/IF-BREAK of Dynamic Control Fields ............................................................. 114 Parameter Transfer with Dynamic Variables ......................................................... 115 Work File Access with Large and Dynamic Variables ........................................... 118 Performance Aspects with Dynamic Variables ...................................................... 118 Outputting Dynamic Variables .............................................................................. 119 Dynamic X-Arrays .................................................................................................. 120 19 User-Defined Constants ............................................................................................. 121 Numeric Constants ................................................................................................. 122 Alphanumeric Constants ....................................................................................... 123 Unicode Constants ................................................................................................. 124 Date and Time Constants ....................................................................................... 127 Hexadecimal Constants .......................................................................................... 129 Logical Constants ................................................................................................... 130
iv
Programming Guide
Programming Guide Floating Point Constants ........................................................................................ 131 Attribute Constants ................................................................................................ 131 Handle Constants ................................................................................................... 132 Defining Named Constants .................................................................................... 132 20 Initial Values (and the RESET Statement) .................................................................. 135 Default Initial Value of a User-Defined Variable/Array ......................................... 136 Assigning an Initial Value to a User-Defined Variable/Array ................................ 136 Resetting a User-Defined Variable to its Initial Value ............................................ 138 21 Redefining Fields ....................................................................................................... 141 Using the REDEFINE Option of DEFINE DATA ................................................... 142 Example Program Illustrating the Use of a Redefinition ....................................... 143 22 Arrays ........................................................................................................................ 145 Defining Arrays ...................................................................................................... 146 Initial Values for Arrays ......................................................................................... 147 Assigning Initial Values to One-Dimensional Arrays ............................................ 147 Assigning Initial Values to Two-Dimensional Arrays ............................................ 148 A Three-Dimensional Array ................................................................................... 152 Arrays as Part of a Larger Data Structure .............................................................. 154 Database Arrays ..................................................................................................... 155 Using Arithmetic Expressions in Index Notation .................................................. 155 Arithmetic Support for Arrays ............................................................................... 156 23 X-Arrays ..................................................................................................................... 159 Definition ................................................................................................................ 160 Storage Management of X-Arrays .......................................................................... 161 Storage Management of X-Group Arrays .............................................................. 161 Referencing an X-Array .......................................................................................... 163 Parameter Transfer with X-Arrays ......................................................................... 164 Parameter Transfer with X-Group Arrays .............................................................. 165 X-Array of Dynamic Variables ............................................................................... 166 Lower and Upper Bound of an Array .................................................................... 167 24 Accessing Data in a Database .................................................................................... 169 25 Natural and Database Access .................................................................................... 171 Database Management Systems Supported by Natural ........................................ 172 Profile Parameters Influencing Database Access ................................................... 173 Access through Data Definition Modules .............................................................. 173 Natural's Data Manipulation Language ................................................................ 174 Natural's Special SQL Statements .......................................................................... 175 26 Accessing Data in an Adabas Database ..................................................................... 177 Data Definition Modules - DDMs .......................................................................... 178 Database Arrays ..................................................................................................... 180 DEFINE DATA Views ............................................................................................ 185 Statements for Database Access ............................................................................. 187 Multi-Fetch Clause ................................................................................................. 200 Database Processing Loops .................................................................................... 203 Database Update - Transaction Processing ............................................................ 209
Programming Guide
Programming Guide Selecting Records Using ACCEPT/REJECT ........................................................... 217 AT START/END OF DATA Statements .................................................................. 220 Unicode Data .......................................................................................................... 223 27 Accessing Data in an SQL Database .......................................................................... 225 28 Accessing Data in a VSAM Database ........................................................................ 227 29 Accessing Data in a DL/I Database ............................................................................ 229 30 Controlling Data Output ........................................................................................... 231 31 Report Specification - (rep) Notation ......................................................................... 233 Use of Report Specifications ................................................................................... 234 Statements Concerned ............................................................................................ 234 Examples of Report Specification ........................................................................... 234 32 Layout of an Output Page .......................................................................................... 235 Statements Influencing a Report Layout ................................................................ 236 General Layout Example ........................................................................................ 237 33 Statements DISPLAY and WRITE .............................................................................. 239 DISPLAY Statement ................................................................................................ 240 WRITE Statement ................................................................................................... 241 Example of DISPLAY Statement ............................................................................ 242 Example of WRITE Statement ................................................................................ 243 Column Spacing - SF Parameter and nX Notation ................................................. 243 Tab Setting - nT Notation ....................................................................................... 245 Line Advance - Slash Notation ............................................................................... 245 Further Examples of DISPLAY and WRITE Statements ........................................ 248 34 Index Notation for Multiple-Value Fields and Periodic Groups ............................... 249 Use of Index Notation ............................................................................................ 250 Example of Index Notation in DISPLAY Statement ............................................... 250 Example of Index Notation in WRITE Statement .................................................. 251 35 Page Titles, Page Breaks, Blank Lines ........................................................................ 253 Default Page Title ................................................................................................... 254 Suppress Page Title - NOTITLE Option ................................................................. 254 Define Your Own Page Title - WRITE TITLE Statement ........................................ 255 Logical Page and Physical Page ............................................................................. 258 Page Size - PS Parameter ........................................................................................ 260 Page Advance ......................................................................................................... 260 New Page with Title ............................................................................................... 263 Page Trailer - WRITE TRAILER Statement ............................................................ 264 Generating Blank Lines - SKIP Statement .............................................................. 266 AT TOP OF PAGE Statement ................................................................................. 268 AT END OF PAGE Statement ................................................................................. 269 Further Example ..................................................................................................... 270 36 Column Headers ........................................................................................................ 271 Default Column Headers ....................................................................................... 272 Suppress Default Column Headers - NOHDR Option .......................................... 273 Define Your Own Column Headers ....................................................................... 273 Combining NOTITLE and NOHDR ....................................................................... 274
vi
Programming Guide
Programming Guide Centering of Column Headers - HC Parameter ..................................................... 274 Width of Column Headers - HW Parameter .......................................................... 275 Filler Characters for Headers - Parameters FC and GC ......................................... 275 Underlining Character for Titles and Headers - UC Parameter ............................ 276 Suppressing Column Headers - Slash Notation .................................................... 277 Further Examples of Column Headers .................................................................. 278 37 Parameters to Influence the Output of Fields ............................................................ 279 Overview of Field-Output-Relevant Parameters ................................................... 280 Leading Characters - LC Parameter ....................................................................... 280 Insertion Characters - IC Parameter ....................................................................... 281 Trailing Characters - TC Parameter ........................................................................ 281 Output Length - AL and NL Parameters ............................................................... 282 Display Length for Output - DL Parameter ........................................................... 282 Sign Position - SG Parameter .................................................................................. 284 Identical Suppress - IS Parameter ........................................................................... 286 Zero Printing - ZP Parameter ................................................................................. 288 Empty Line Suppression - ES Parameter ............................................................... 288 Further Examples of Field-Output-Relevant Parameters ...................................... 290 38 Edit Masks - EM Parameter ....................................................................................... 293 Use of EM Parameter .............................................................................................. 294 Edit Masks for Numeric Fields ............................................................................... 294 Edit Masks for Alphanumeric Fields ..................................................................... 295 Length of Fields ...................................................................................................... 295 Edit Masks for Date and Time Fields ..................................................................... 296 Customizing Separator Character Displays ........................................................... 296 Examples of Edit Masks ......................................................................................... 298 Further Examples of Edit Masks ............................................................................ 300 39 Vertical Displays ........................................................................................................ 301 Creating Vertical Displays ...................................................................................... 302 Combining DISPLAY and WRITE .......................................................................... 302 Tab Notation - T*field ............................................................................................. 303 Positioning Notation x/y ........................................................................................ 304 DISPLAY VERT Statement ..................................................................................... 305 Further Example of DISPLAY VERT with WRITE Statement ................................ 311 40 Further Programming Aspects .................................................................................. 313 41 End of Statement, Program or Application ............................................................... 315 End of Statement .................................................................................................... 316 End of Program ...................................................................................................... 316 End of Application ................................................................................................. 316 42 Processing of Application Errors ............................................................................... 317 Natural's Default Error Processing ........................................................................ 318 Application Specific Error Processing .................................................................... 318 Using an ON ERROR Statement Block .................................................................. 319 Using an Error Transaction Program ..................................................................... 320 Error Processing Related Features ......................................................................... 323
Programming Guide
vii
Programming Guide 43 Conditional Processing - IF Statement ...................................................................... 329 Structure of IF Statement ........................................................................................ 330 Nested IF Statements .............................................................................................. 332 44 Loop Processing ......................................................................................................... 335 Use of Processing Loops ......................................................................................... 336 Limiting Database Loops ....................................................................................... 336 Limiting Non-Database Loops - REPEAT Statement ............................................. 338 Example of REPEAT Statement .............................................................................. 339 Terminating a Processing Loop - ESCAPE Statement ............................................ 340 Loops Within Loops ............................................................................................... 340 Example of Nested FIND Statements ..................................................................... 341 Referencing Statements within a Program ............................................................. 342 Example of Referencing with Line Numbers ......................................................... 344 Example with Statement Reference Labels ............................................................ 344 45 Control Breaks ........................................................................................................... 347 Use of Control Breaks ............................................................................................. 348 AT BREAK Statement ............................................................................................. 348 Automatic Break Processing .................................................................................. 353 Example of System Functions with AT BREAK Statement .................................... 355 Further Example of AT BREAK Statement ............................................................ 356 BEFORE BREAK PROCESSING Statement ........................................................... 356 Example of BEFORE BREAK PROCESSING Statement ........................................ 356 User-Initiated Break Processing - PERFORM BREAK PROCESSING Statement ................................................................................................................ 357 Example of PERFORM BREAK PROCESSING Statement .................................... 359 46 Data Computation ..................................................................................................... 363 COMPUTE Statement ............................................................................................. 364 Statements MOVE and COMPUTE ........................................................................ 365 Statements ADD, SUBTRACT, MULTIPLY and DIVIDE ....................................... 366 Example of MOVE, SUBTRACT and COMPUTE Statements ............................... 366 COMPRESS Statement ........................................................................................... 367 Example of COMPRESS and MOVE Statements ................................................... 368 Example of COMPRESS Statement ........................................................................ 369 Mathematical Functions ......................................................................................... 370 Further Examples of COMPUTE, MOVE and COMPRESS Statements ................ 371 47 System Variables and System Functions ................................................................... 373 System Variables ..................................................................................................... 374 System Functions .................................................................................................... 376 Example of System Variables and System Functions ............................................. 376 Further Examples of System Variables ................................................................... 378 Further Examples of System Functions .................................................................. 378 48 Stack ........................................................................................................................... 379 Use of Natural Stack ............................................................................................... 380 Stack Processing ..................................................................................................... 380 Placing Data on the Stack ....................................................................................... 381
viii
Programming Guide
Programming Guide Deleting the First Entry from the Stack .................................................................. 382 Clearing the Stack ................................................................................................... 382 49 Processing of Date Information ................................................................................. 383 Edit Masks for Date Fields and Date System Variables ......................................... 384 Default Edit Mask for Date - DTFORM Parameter ................................................ 384 Date Format for Alphanumeric Representation - DF Parameter ........................... 385 Date Format for Output - DFOUT Parameter ........................................................ 388 Date Format for Stack - DFSTACK Parameter ....................................................... 389 Year Sliding Window - YSLW Parameter ............................................................... 390 Combinations of DFSTACK and YSLW ................................................................. 392 Year Fixed Window ................................................................................................ 395 Date Format for Default Page Title - DFTITLE Parameter ..................................... 395 50 Text Notation ............................................................................................................. 397 Defining a Text to Be Used with a Statement - the 'text' Notation ......................... 398 Defining a Character to Be Displayed n Times before a Field Value - the 'c'(n) Notation .................................................................................................................. 400 51 User Comments ......................................................................................................... 401 Using an Entire Source Code Line for Comments ................................................. 402 Using the Latter Part of a Source Code Line for Comments .................................. 403 52 Logical Condition Criteria ......................................................................................... 405 Introduction ............................................................................................................ 406 Relational Expression ............................................................................................. 407 Extended Relational Expression ............................................................................. 411 Evaluation of a Logical Variable ............................................................................. 412 Fields Used within Logical Condition Criteria ...................................................... 413 Logical Operators in Complex Logical Expressions .............................................. 415 BREAK Option - Compare Current Value with Value of Previous Loop Pass ...... 417 IS Option - Check whether Content of Alphanumeric or Unicode Field can be Converted ............................................................................................................... 419 MASK Option - Check Selected Positions of a Field for Specific Content ............. 421 MASK Option Compared with IS Option .............................................................. 428 MODIFIED Option - Check whether Field Content has been Modified ............... 430 SCAN Option - Scan for a Value within a Field ..................................................... 432 SPECIFIED Option - Check whether a Value is Passed for an Optional Parameter ................................................................................................................ 434 53 Rules for Arithmetic Assignment .............................................................................. 437 Field Initialization .................................................................................................. 438 Data Transfer .......................................................................................................... 438 Field Truncation and Field Rounding .................................................................... 441 Result Format and Length in Arithmetic Operations ............................................ 441 Arithmetic Operations with Floating-Point Numbers ........................................... 442 Arithmetic Operations with Date and Time .......................................................... 444 Performance Considerations for Mixed Format Expressions ................................ 448 Precision of Results for Arithmetic Operations ..................................................... 448 Error Conditions in Arithmetic Operations ........................................................... 449
Programming Guide
ix
Programming Guide Processing of Arrays ............................................................................................... 450 54 Compilation Aspects .................................................................................................. 457 Compiler Options and Parameters ......................................................................... 458 Other Parameters Influencing the Compiler .......................................................... 459 55 Statements for Internet and XML Access .................................................................. 461 Statements Available .............................................................................................. 462 General Prerequisites ............................................................................................. 469 HTTPS Support for the REQUEST DOCUMENT Statement under z/OS ............. 472 Restriction Concerning IMS TM ............................................................................. 475 Preconditions for the Support of XML-Related Statements under openUTM ...... 475 Sample Program ..................................................................................................... 476 Frequently Asked Questions .................................................................................. 479 References ............................................................................................................... 486 56 Designing Application User Interfaces ...................................................................... 487 57 Screen Design ............................................................................................................. 489 Control of Function-Key Lines - Terminal Command %Y ..................................... 490 Control of the Message Line - Terminal Command %M ....................................... 494 Assigning Colors to Fields - Terminal Command %= ............................................ 497 Outlining - Terminal Command %D=B .................................................................. 498 Statistics Line/Infoline - Terminal Command %X .................................................. 498 Windows ................................................................................................................. 500 Standard/Dynamic Layout Maps ........................................................................... 509 Multilingual User Interfaces ................................................................................... 510 Skill-Sensitive User Interfaces ................................................................................ 515 58 Dialog Design ............................................................................................................ 517 Field-Sensitive Processing ...................................................................................... 518 Simplifying Programming ...................................................................................... 520 Line-Sensitive Processing ....................................................................................... 521 Column-Sensitive Processing ................................................................................. 522 Processing Based on Function Keys ....................................................................... 523 Processing Based on Function-Key Names ............................................................ 524 Processing Data Outside an Active Window ......................................................... 524 Copying Data from a Screen .................................................................................. 527 Statements REINPUT/REINPUT FULL ................................................................. 531 Object-Oriented Processing - The Natural Command Processor .......................... 532 59 NaturalX ..................................................................................................................... 533 60 Introduction to NaturalX ........................................................................................... 535 Why NaturalX? ....................................................................................................... 536 61 Developing NaturalX Applications ........................................................................... 537 Development Environments .................................................................................. 538 Defining Classes ..................................................................................................... 538 Using Classes and Objects ...................................................................................... 543 62 Natural Reserved Keywords ..................................................................................... 547 Alphabetical List of Natural Reserved Keywords ................................................. 548 Performing a Check for Natural Reserved Keywords ........................................... 563
Programming Guide
Programming Guide 63 Referenced Example Programs .................................................................................. 567 READ Statement ..................................................................................................... 568 FIND Statement ...................................................................................................... 569 Nested READ and FIND Statements ..................................................................... 573 ACCEPT and REJECT Statements .......................................................................... 575 AT START OF DATA and AT END OF DATA Statements .................................... 577 DISPLAY and WRITE Statements .......................................................................... 580 DISPLAY Statement ................................................................................................ 584 Column Headers .................................................................................................... 585 Field-Output-Relevant Parameters ........................................................................ 587 Edit Masks .............................................................................................................. 593 DISPLAY VERT with WRITE Statement ................................................................ 596 AT BREAK Statement ............................................................................................. 597 COMPUTE, MOVE and COMPRESS Statements .................................................. 598 System Variables ..................................................................................................... 601 System Functions .................................................................................................... 604 Index ............................................................................................................................... 607
Programming Guide
xi
xii
Programming Guide
This guide is complemental to the Natural reference documentation in that it provides basic information and some longer, in-depth articles on various aspects of programming with Natural. You should be familiar with this information before you start to write Natural applications. See also First Steps. This tutorial contains a series of sessions which introduce you to some of the basics of Natural programming.
Natural Programming Modes Describes the differences between the two Natural programming modes: Reporting Mode and Structured Mode. Generally, it is recommended to use structured mode exclusively, because it provides for more clearly structured applications. Therefore all explanations and examples in this documentation refer to structured mode. Any peculiarities of reporting mode will not be taken into consideration. Object Types Within an application, you can use several types of programming objects to achieve an efficient application structure. This document discusses the various types of Natural programming objects, such as data areas, programs, subprograms, subroutines, helproutines, maps. Describes how you define the fields you wish to use in a program. Describes various aspects of using Natural to access data in an Adabas database and in various non-Adabas databases supported by Natural. On principle, the features and examples described for Adabas also apply to other database management systems. Differences, if any, are described in the relevant interface documentation and in the Statements documentation or Parameter Reference. Controlling Data Output Further Programming Aspects Discusses various aspects of how you can control the format of an output report created with Natural, that is, the way in which the data are displayed. Discusses various other aspects of programming with Natural.
Programming Guide
Statements for Internet Gives an overview of the Natural statements for internet and XML access, and XML Access specifies the general prerequisites for using these statements in a mainframe environment and informs about the general restrictions that apply. Designing Application Provides information on components of Natural which you can use to design User Interfaces user interfaces for your applications. NaturalX Natural Reserved Keywords Referenced Example Programs Describes how to develop object-based applications. Contains a list of all keywords and words that are reserved in the Natural programming language. The previous sections of the Programming Guide contain several examples of Natural programs. In addition, links are provided there to further example programs (mainly for reporting mode) which are contained in this separate section.
Note:
1. All example programs shown in the Programming Guide are also provided in source-code form in the Natural library SYSEXPG. The example programs use data from the files EMPLOYEES and VEHICLES, which are supplied by Software AG for demonstration purposes. 2. Further example programs of using Natural statements are provided in the Natural library SYSEXSYN and are documented in the section Referenced Example Programs in the Statements documentation. 3. Please ask your Natural administrator about the availability of the libraries SYSEXPG and SYSEXSYN at your site. 4. To use any Natural example program to access an Adabas database, the Adabas nucleus parameter OPTIONS must be set to TRUNCATION.
Note: For information on Natural Application Programming Interfaces (APIs), see: SYSEXT - Natural Application Programming Interfaces and SYSAPI - APIs of Natural Add-On Products in the Utilities documentation.
Programming Guide
Purpose of Programming Modes .......................................................................................................... 4 Setting/Changing the Programming Mode .............................................................................................. 5 Functional Differences ....................................................................................................................... 5
Note: Generally, it is recommended to use structured mode exclusively, because it provides for more clearly structured applications.
Reporting Mode
Reporting mode is only useful for the creation of adhoc reports and small programs which do not involve complex data and/or programming constructs. (If you decide to write a program in reporting mode, be aware that small programs may easily become larger and more complex.) Please note that certain Natural statements are available only in reporting mode, whereas others have a specific structure when used in reporting mode. For an overview of the statements that can be used in reporting mode, see Reporting Mode Statements in the Statements documentation.
Structured Mode
Structured mode is intended for the implementation of complex applications with a clear and well-defined program structure. The major benefits of structured mode are:
The programs have to be written in a more structured way and are therefore easier to read and consequently easier to maintain. As all fields to be used in a program have to be defined in one central location (instead of being scattered all over the program, as is possible in reporting mode), overall control of the data used is much easier.
With structured mode, you also have to make more detail planning before the actual programs can be coded, thereby avoiding many programming errors and inefficiencies. For an overview of the statements that can be used in structured mode, see Statements Grouped by Functions in the Statements documentation.
Programming Guide
For further information on the Natural profile and session parameter SM, see SM - Programming in Structured Mode in the Parameter Reference. For information on how to change the programming mode, see Programming Modes in Using Natural and SM - Programming in Structured Mode in the Parameter Reference.
Functional Differences
The following major functional differences exist between reporting mode and structured mode:
Syntax Related to Closing Loops and Functional Blocks Closing a Processing Loop in Reporting Mode Closing a Processing Loop in Structured Mode Location of Data Elements in a Program Database Reference
Note: For detailed information on functional differences that exist between the two modes, see the Statements documentation. It provides separate syntax diagrams and syntax element descriptions for each mode-sensitive statement. For a functional overview of the statements that can be used in reporting mode, see Reporting Mode Statements in the Statements documentation.
used. Structured Mode: Every loop or logical construct must be explicitly closed with a corresponding END-... statement. Thus, it becomes immediately clear, which loop/logical constructs ends where.
LOOP and DO/DOEND statements cannot be used.
Programming Guide
Natural Programming Modes The two examples below illustrate the differences between the two modes in constructing processing loops and logical conditions. Reporting Mode Example: The reporting mode example uses the statements DO and DOEND to mark the beginning and end of the statement block that is based on the AT END OF DATA condition. The END statement closes all active processing loops.
READ EMPLOYEES BY PERSONNEL-ID DISPLAY NAME BIRTH AT END OF DATA DO SKIP 2 WRITE / 'LAST SELECTED:' OLD(NAME) DOEND END
Structured Mode Example: The structured mode example uses an END-ENDDATA statement to close the AT END OF DATA condition, and an END-READ statement to close the READ loop. The result is a more clearly structured program in which you can see immediately where each construct begins and ends:
DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH END-DEFINE READ MYVIEW BY PERSONNEL-ID DISPLAY NAME BIRTH AT END OF DATA SKIP 2 WRITE / 'LAST SELECTED:' OLD(NAME) END-ENDDATA END-READ END
Programming Guide
Example 2 - END:
FIND ... FIND ... ... ... END
Example 3 - SORT:
FIND ... FIND ... ... ... SORT ... ... END
/* closes all loops, initiates loop /* closes SORT loop and ends processing
Programming Guide
Example 2 - READ:
READ ... AT END OF DATA ... END-ENDDATA ... END-READ ... ... END
Example 3 - SORT:
READ ... FIND ... ... ... END-ALL SORT ... ... END-SORT END
Programming Guide
Database Reference
Reporting Mode: In reporting mode, database fields and DDMs may be referenced without having been defined in a data area.
Programming Guide
Natural Programming Modes Structured Mode: In structured mode, each database field to be used must be specified in a DEFINE DATA statement as described in Defining Fields and Accessing Data in an Adabas Database.
10
Programming Guide
Object Types
This part describes the various types of Natural programming objects that can be used to achieve an efficient application structure. All Natural objects are stored in Natural libraries. Natural libraries are contained in Natural system files.
Using Natural Programming Objects Data Areas Programs, Subprograms and Subroutines Processing a Rich GUI Page - Adapter Maps Helproutines Multiple Use of Source Code - Copycode Documenting Natural Objects - Text Creating Component Based Applications - Class Using Non-Natural Files - Resource
11
12
Types of Natural Programming Objects ................................................................................................ 14 Creating and Maintaining Programming Objects .................................................................................... 14
13
Program Class Subprogram Adapter Subroutine Copycode Helproutine Text Map Local Data Area Global Data Area Parameter Data Area
Local data areas, global data areas and parameter data areas are created/maintained with the data area editor. Maps are created/maintained with the map editor. Classes are created/maintained with the program editor. All other types of objects listed above are created/maintained with the program editor.
For information about the naming conventions that apply to Natural objects, see Object Naming Conventions. For detailed information on using these programming objects, see Maintaining and Executing Natural Objects in Using Natural.
14
Programming Guide
Data Areas
Use of Data Areas ........................................................................................................................... 16 Local Data Area .............................................................................................................................. 16 Global Data Area ............................................................................................................................. 18 Parameter Data Area ....................................................................................................................... 26
15
Data Areas
Define local data within a program. Define local data outside a program in a separate Natural programming object, a local data area (LDA). Such a local data area is initialized when a program, subprogram or external subroutine that uses this local data area starts to execute.
For a clear application structure and for easier maintainability, it is usually better to define fields in data areas outside the programs.
16
Programming Guide
Data Areas Example 1 - Fields Defined Directly within a DEFINE DATA Statement: In the following example, the fields are defined directly within the DEFINE DATA statement of the program.
DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 PERSONNEL-ID 1 #VARI-A (A20) 1 #VARI-B (N3.2) 1 #VARI-C (I4) END-DEFINE ...
Example 2 - Fields Defined in a Separate Data Area: In the following example, the same fields are not defined in the DEFINE DATA statement of the program, but in an LDA, named LDA39, and the DEFINE DATA statement in the program contains only a reference to that data area. Program:
DEFINE DATA LOCAL USING LDA39 END-DEFINE ...
Programming Guide
17
Data Areas
Creating and Referencing a GDA Creating and Deleting GDA Instances Data Blocks
A subprogram that references a GDA (any GDA) is invoked with a CALLNAT statement.
18
Programming Guide
Data Areas
A subprogram that does not reference a GDA invokes a programming object that references a GDA (any GDA).
If a new instance of a GDA is created, the current GDA instance is suspended and the data values it contains are stacked. The subprogram then references the data values in the newly created GDA instance. The data values in the suspended GDA instance or instances is inaccessible. A programming object only refers to one GDA instance and cannot access any previous GDA instances. A GDA data element can only be passed to a subprogram by defining the element as a parameter in the CALLNAT statement. When the subprogram returns to the invoking programming object, the GDA instance it references is deleted and the GDA instance suspended previously is resumed with its data values. A GDA instance and its contents is deleted if any of the following applies:
The next LOGON is performed. Another GDA is referenced on the same level (levels are described later in this section). A RELEASE VARIABLES statement is executed. In this case, the data values in a GDA instance are reset either when a program at the level 1 finishes executing, or if the program invokes another program via a FETCH or RUN statement. The following graphics illustrate how programming objects reference GDAs and share data elements in GDA instances.
Sharing GDA Instances The graphic below illustrates that a subprogram referencing a GDA cannot share the data values in a GDA instance referenced by the invoking program. A subprogram that references the same GDA as the invoking program creates a new instance of this GDA. The data elements defined in a GDA that is referenced by a subprogram can, however, be shared by a subroutine or a helproutine invoked by the subprogram. The graphic below shows three GDA instances of GDA1 and the final values each GDA instance is assigned by the data element #GLOB1. The numbers of the programming objects. to indicate the hierarchical levels
Programming Guide
19
Data Areas
Using FETCH or FETCH RETURN The graphic below illustrates that programs referencing the same GDA and invoking one another with the FETCH or FETCH RETURN statement share the data elements defined in this GDA. If any of these programs does not reference a GDA, the instance of the GDA referenced previously remains active and the values of the data elements are retained.
20
Programming Guide
Data Areas
The numbers
and
Using FETCH with different GDAs The graphic below illustrates that if a program uses the FETCH statement to invoke another program that references a different GDA, the current instance of the GDA (here: GDA1) referenced by the invoking program is deleted. If this GDA is then referenced again by another program, a new instance of this GDA is created where all data elements have their initial values. You cannot use the FETCH RETURN statement to invoke another program that references a different GDA. The number indicates the hierarchical level of the programming objects.
The invoking programs PROG3 and PROG4 affect the GDA instances as follows:
The statement GLOBAL USING GDA2 in PROG3 creates an instance of GDA2 and deletes the current instance of GDA1. The statement GLOBAL USING GDA1 in PROG4 deletes the current instance of GDA2 and creates a new instance of GDA1. As a result, the WRITE statement displays the value zero (0).
Programming Guide
21
Data Areas
Data Blocks
To save data storage space, you can create a GDA with data blocks. The following topics are covered below:
Example of Data Block Usage Data blocks can overlay each other during program execution, thereby saving storage space.
22
Programming Guide
Data Areas For example, given the following hierarchy, Blocks B and C would be assigned the same storage area. Thus it would not be possible for Blocks B and C to be in use at the same time. Modifying Block B would result in destroying the contents of Block C.
Defining Data Blocks You define data blocks in the data area editor. You establish the block hierarchy by specifying which block is subordinate to which: you do this by entering the name of the parent block in the comment field of the block definition. In the following example, SUB-BLOCKB and SUB-BLOCKC are subordinate to MASTER-BLOCKA; SUB-BLOCKD is subordinate to SUB-BLOCKB. The maximum number of block levels is 8 (including the master block). Example: Global Data Area G-BLOCK:
Programming Guide
23
Data Areas
I T L - - B 1 B 1 B 1 B 1
To make the specific blocks available to a program, you use the following syntax in the DEFINE DATA statement: Program 1:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA END-DEFINE
Program 2:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA.SUB-BLOCKB END-DEFINE
Program 3:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA.SUB-BLOCKC END-DEFINE
Program 4:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA.SUB-BLOCKB.SUB-BLOCKD END-DEFINE
With this structure, Program 1 can share the data in MASTER-BLOCKA with Program 2, Program 3 or Program 4. However, Programs 2 and 3 cannot share the data areas of SUB-BLOCKB and SUB-BLOCKC because these data blocks are defined at the same level of the structure and thus occupy the same storage area.
24
Programming Guide
Data Areas Block Hierarchies Care needs to be taken when using data block hierarchies. Let us assume the following scenario with three programs using a data block hierarchy: Program 1:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA.SUB-BLOCKB END-DEFINE * MOVE 1234 TO SBB-DATA01 FETCH 'PROGRAM2' END
Program 2:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA END-DEFINE * FETCH 'PROGRAM3' END
Program 3:
DEFINE DATA GLOBAL USING G-BLOCK WITH MASTER-BLOCKA.SUB-BLOCKB END-DEFINE * WRITE SBB-DATA01 END
Explanation:
Program 1 uses the global data area G-BLOCK with MASTER-BLOCKA and SUB-BLOCKB. The program modifies a field in SUB-BLOCKB and FETCHes Program 2 which specifies only MASTER-BLOCKA in its data definition. Program 2 resets (deletes the contents of) SUB-BLOCKB. The reason is that a program on Level 1 (for example, a program called with a FETCH statement) resets any data blocks that are subordinate to the blocks it defines in its own data definition. Program 2 now FETCHes Program 3 which is to display the field modified in Program 1, but it returns an empty screen.
Programming Guide
25
Data Areas For details on program levels, see Multiple Levels of Invoked Objects.
they can be defined in the PARAMETER clause of the DEFINE DATA statement itself; or they can be defined in a separate parameter data area, with the DEFINE DATA PARAMETER statement referencing that PDA.
26
Programming Guide
Data Areas
Programming Guide
27
Data Areas
In the same way, parameters that are passed to an external subroutine via a PERFORM statement must be defined with a DEFINE DATA PARAMETER statement in the external subroutine. In the invoking object, the parameter variables passed to the subprogram/subroutine need not be defined in a PDA; in the illustrations above, they are defined in the LDA used by the invoking object (but they could also be defined in a GDA). The sequence, format and length of the parameters specified with the CALLNAT/PERFORM statement in the invoking object must exactly match the sequence, format and length of the fields specified in the DEFINE DATA PARAMETER statement of the invoked subprogram/subroutine. However, the names of the variables in the invoking object and the invoked subprogram/subroutine need not be the same (as the parameter data are transferred by address, not by name). To guarantee that the data element definitions used in the invoking program are identical to the data element definitions used in the subprogram or external subroutine, you can specify a PDA
28
Programming Guide
Data Areas in a DEFINE DATA LOCAL USING statement. By using a PDA as an LDA you can avoid the extra effort of creating an LDA that has the same structure as the PDA.
Programming Guide
29
30
A Modular Application Structure ......................................................................................................... 32 Multiple Levels of Invoked Objects ...................................................................................................... 32 Program ........................................................................................................................................ 34 Subroutine ..................................................................................................................................... 37 Subprogram ................................................................................................................................... 42 Processing Flow when Invoking a Routine ............................................................................................ 44
31
Programs, Subprograms and Subroutines This document discusses those object types which can be invoked as routines; that is, as subordinate programs. Helproutines and maps, although they are also invoked from other objects, are strictly speaking not routines as such, and are therefore discussed in separate documents; see Helproutines and Maps.
32
Programming Guide
Programs, Subprograms and Subroutines The following illustration is an example of multiple levels of invoked objects and also shows how these levels are counted:
If you wish to ascertain the level number of the object that is currently being executed, you can use the system variable *LEVEL (which is described in the System Variables documentation). This document discusses the following Natural object types, which can be invoked as routines (that is, subordinate programs):
Helproutines and maps, although they are also invoked from other objects, are strictly speaking not routines as such, and are therefore discussed in separate documents; see Helproutines and Maps. Basically, programs, subprograms and subroutines differ from one another in the way data can be passed between them and in their possibilities of sharing each other's data areas. Therefore the decision which object type to use for which purpose depends very much on the data structure of your application.
Programming Guide
33
Program
A program can be executed - and thus tested - by itself.
To compile and execute a source program, you use the system command RUN. To execute a program that already exists in compiled form, you use the system command EXECUTE.
A program can also be invoked from another object with a FETCH or FETCH RETURN statement. The invoking object can be another program, a subprogram, subroutine or helproutine.
When a program is invoked with FETCH RETURN, the execution of the invoking object will be suspended - not terminated - and the FETCHed program will be activated as a subordinate program. When the execution of the FETCHed program is terminated, the invoking object will be re-activated and its execution continued with the statement following the FETCH RETURN statement. When a program is invoked with FETCH, the execution of the invoking object will be terminated and the FETCHed program will be activated as a main program. The invoking object will not be re-activated upon termination of the FETCHed program.
34
Programming Guide
A program invoked with FETCH RETURN can access the global data area used by the invoking object. In addition, every program can have its own local data area, in which the fields that are to be used only within the program are defined.
Programming Guide
35
Programs, Subprograms and Subroutines However, a program invoked with FETCH RETURN cannot have its own global data area.
A program invoked with FETCH as a main program usually establishes its own global data area (as shown in the illustration above). However, it could also use the same global data area as established by the invoking object. Note: A source program can also be invoked with a RUN statement; see the RUN statement in the Statements documentation.
36
Programming Guide
Subroutine
The statements that make up a subroutine must be defined within a DEFINE SUBROUTINE ... END-SUBROUTINE statement block. A subroutine is invoked with a PERFORM statement. A subroutine may be an inline subroutine or an external subroutine:
Inline Subroutine An inline subroutine is defined within the object which contains the PERFORM statement that invokes it. External Subroutine An external subroutine is defined in a separate object - of type subroutine - outside the object which invokes it.
If you have a block of code which is to be executed several times within an object, it is useful to use an inline subroutine. You then only have to code this block once within a DEFINE SUBROUTINE statement block and invoke it with several PERFORM statements. The following topics are covered below:
Programming Guide
37
Inline Subroutine
38
Programming Guide
Programming Guide
39
Programs, Subprograms and Subroutines An inline subroutine can be contained within a programming object of type program, subprogram, subroutine or helproutine. If an inline subroutine is so large that it impairs the readability of the object in which it is contained, you may consider putting it into an external subroutine, so as to enhance the readability of your application.
40
Programming Guide
External Subroutine
An external subroutine - that is, an object of type subroutine - cannot be executed by itself. It must be invoked from another object. The invoking object can be a program, subprogram, subroutine or helproutine.
Programming Guide
41
Subprogram
Typically, a subprogram would contain a generally available standard function that is used by various objects in an application. A subprogram cannot be executed by itself. It must be invoked from another object. The invoking object can be a program, subprogram, subroutine or helproutine. A subprogram is invoked with a CALLNAT statement. When the CALLNAT statement is executed, the execution of the invoking object will be suspended and the subprogram executed. After the subprogram has been executed, the execution of the invoking object will be continued with the statement following the CALLNAT statement.
42
Programming Guide
In addition, a subprogram can have its own local data area, in which the fields to be used within the subprogram are defined. If a subprogram in turn invokes a subroutine or helproutine, it can also establish its own global data area to be shared with the subroutine/helproutine.
Programming Guide
43
44
Programming Guide
Programming Guide
45
46
The Natural object of type adapter is used to represent a rich GUI page in a Natural application. This object type plays a similar role for the processing of a rich GUI page as the object type map plays for terminal I/O processing. But it is different from a map in that it does not contain layout information. An object of type adapter is generated from an external page layout. It serves as an interface that enables a Natural application to send data to an external I/O system for presentation and modification, using an externally defined and stored page layout. The adapter contains the Natural code necessary to perform this task. An application program refers to an adapter in the PROCESS PAGE USING statement. For information on the object type adapter, see the Natural for Ajax documentation.
47
48
Maps
Benefits of Using Maps ..................................................................................................................... 50 Types of Maps ................................................................................................................................ 50 Creating Maps ................................................................................................................................ 51 Starting/Stopping Map Processing ...................................................................................................... 51
49
Maps As an alternative to specifying screen layouts dynamically, the INPUT statement offers the possibility to use predefined map layouts which makes use of the Natural object type map.
Clearly structured applications as a result of a consequent separation of program logic and display logic. Map layout modifications possible without making changes to the main programs. The language of an applications's user interface can be easily adapted for internationalization or localization.
The benefit of using programming objects such as maps will become obvious when it comes to maintaining existing Natural applications.
Types of Maps
Maps (screen layouts) are those parts of an application which the users see on their screens. The following types of maps exist:
Input Map The dialog with the user is carried out via input maps. Output Map If an application produces any output report, this report can be displayed on the screen by using an output map. Help Map Help maps are, in principle, like any other maps, but when they are assigned as help, additional checks are performed to ensure their usability for help purpose.
the map body which defines the screen layout and an associated parameter data area (PDA) which, as a sort of interface, contains data definitions such as name, format, length of each field presented on a specific map.
Related Topics:
50
Programming Guide
Maps
For information on selection boxes that can be attached to input fields, see SB - Selection Box in the INPUT statement documentation and SB - Selection Box in the Parameter Reference. For information on split screen maps where the upper portion may be used as an output map and the lower portion as an input map, see Split-Screen Feature in the INPUT statement documentation.
Creating Maps
Maps and help map layouts are created and edited in the map editor. The appropriate LDA is created and maintained in the data area editor. Depending on the platform on which Natural is installed, these editors have either a character user interface or a graphical user interface. Related Topics:
For information on using the data area editor, see Data Area Editor in the platform-specific Editors documentation. For information on using the map editor, see Map Editor in the platform-specific Editors documentation. For a comprehensive description of the full range of possibilities provided by the Natural map editor (character-user-interface version), see Map Editor Tutorial. For information on input processing using screen layouts specified dynamically, see Syntax 1 Dynamic Screen Layout Specification in the INPUT statement documentation. For information on input processing using a map layout created with the map editor, see Syntax 2 - Using Predefined Map Layout in the INPUT statement documentation.
Programming Guide
51
52
Helproutines
Invoking Help ................................................................................................................................. 54 Specifying Helproutines .................................................................................................................... 54 Programming Considerations for Helproutines ....................................................................................... 55 Passing Parameters to Helproutines ................................................................................................... 55 Equal Sign Option ........................................................................................................................... 56 Array Indices .................................................................................................................................. 57 Help as a Window ........................................................................................................................... 57
53
Helproutines Helproutines have specific characteristics to facilitate the processing of help requests. They may be used to implement complex and interactive help systems. They are created with the program editor.
Invoking Help
A Natural user can invoke a Natural helproutine either by entering the help character in a field, or by pressing the help key (usually PF1). The default help character is a question mark (?).
The help character must be entered only once. The help character must be the only character modified in the input string. The help character must be the first character in the input string.
If a helproutine is specified for a numeric field, Natural will allow a question mark to be entered for the purpose of invoking the helproutine for that field. Natural will still check that valid numeric data are provided as field input. If not already specified, the help key may be specified with the SET KEY statement:
SET KEY PF1=HELP
A helproutine can only be invoked by a user if it has been specified in the program or map from which it is to be invoked.
Specifying Helproutines
A helproutine may be specified:
in a program: at statement level and at field level; in a map: at map level and at field level.
If a user requests help for a field for which no help has been specified, or if a user requests help without a field being referenced, the helproutine specified at the statement or map level is invoked. A helproutine may also be invoked by using a REINPUT USING HELP statement (either in the program itself or in a processing rule). If the REINPUT USING HELP statement contains a MARK option, the helproutine assigned to the MARKed field is invoked. If no field-specific helproutine is assigned, the map helproutine is invoked. A REINPUT statement in a helproutine may only apply to INPUT statements within the same helproutine.
54
Programming Guide
Helproutines The name of a helproutine may be specified either with the session parameter HE of an INPUT statement:
INPUT (HE='HELP2112')
or using the extending field editing facility of the map editor (see Creating Maps and the Editors documentation). The name of a helproutine may be specified as an alphanumeric constant or as an alphanumeric variable containing the name. If it is a constant, the name of the helproutine must be specified within apostrophes.
The implicit parameter is the field for which the helproutine was invoked:
INPUT #A (A5) (HE='YOURHELP','001')
Programming Guide
55
Helproutines This is specified within the DEFINE DATA PARAMETER statement of the helproutine as:
Please note that the implicit parameter (#PARM2 in the above example) may be omitted. The implicit parameter is used to access the field for which help was requested, and to return data from the helproutine to the field. For example, you might implement a calculator program as a helproutine and have the result of the calculations returned to the field. When help is called, the helproutine is called before the data are passed from the screen to the program data areas. This means that helproutines cannot access data entered within the same screen transaction. Once help processing is complete, the screen data will be refreshed: any fields which have been modified by the helproutine will be updated - excluding fields which had been modified by the user before the helproutine was invoked, but including the field for which help was requested. Exception: If the field for which help was requested is split into several parts by dynamic attributes (DY session parameter), and the part in which the question mark is entered is after a part modified by the user, the field content will not be modified by the helproutine. Attribute control variables are not evaluated again after the processing of the helproutine, even if they have been modified within the helproutine.
This parameter is processed as an internal field (format/length A65) which contains the field name (or map name if specified at map level). The corresponding helproutine starts with:
This option may be used to access one common helproutine which reads the field name and provides field-specific help by accessing the application online documentation or the Predict data dictionary. 56 Programming Guide
Helproutines
Array Indices
If the field selected by the help character or the help key is an array element, its indices are supplied as implicit parameters (1 - 3 depending on rank, regardless of the explicit parameters). The format/length of these parameters is I2.
INPUT A(*,*) (HE='HELPROUT',=)
DEFINE DATA PARAMETER 1 FNAME (A65) 1 FVALUE (N8) 1 FINDEX1 (I2) 1 FINDEX2 (I2) END-DEFINE ...
/* /* /* /*
contains 'A' value of selected element 1st dimension index 2nd dimension index
Help as a Window
The size of a help to be displayed may be smaller than the screen size. In this case, the help appears on the screen as a window, enclosed by a frame, for example:
******************************************************************************* PERSONNEL INFORMATION PLEASE ENTER NAME: ?_________________ PLEASE ENTER CITY: __________________ +---------------------------+ ! ! ! Type in the name of an ! ! employee in the first ! ! field and press ENTER. ! ! You will then receive ! ! a list of all employees ! ! of that name. ! ! ! ! For a list of employees ! ! of a certain name who ! ! live in a certain city, ! ! type in a name in the ! ! first field and a city !
Programming Guide
57
Helproutines
! in the second field ! ! and press ENTER. ! *******************! !******************************* +---------------------------+
by a FORMAT statement (for example, to specify the page size and line size: FORMAT PS=15 LS=30); by an INPUT USING MAP statement; in this case, the size defined for the map (in its map settings) is used; by a DEFINE WINDOW statement; this statement allows you to either explicitly define a window size or leave it to Natural to automatically determine the size of the window depending on its contents.
The position of a help window is computed automatically from the position of the field for which help was requested. Natural places the window as close as possible to the corresponding field without overlaying the field. With the DEFINE WINDOW statement, you may bypass the automatic positioning and determine the window position yourself. For further information on window processing, please refer to the DEFINE WINDOW statement in the Statements documentation and the terminal command %W in the Terminal Commands documentation.
58
Programming Guide
10
59
Multiple Use of Source Code - Copycode This chapter describes the advantages and the use of copycode.
Use of Copycode
Copycode is a portion of source code which can be included in another object via an INCLUDE statement. So, if you have a statement block which is to appear in identical form in several objects, you may use copycode instead of coding the statement block several times. This reduces the coding effort and also ensures that the blocks are really identical.
Processing of Copycode
The copycode is included at compilation; that is, the source-code lines from the copycode are not physically inserted into the object that contains the INCLUDE statement, but they will be included in the compilation process and are thus part of the resulting object module. Consequently, when you modify the source code of copycode, you also have to newly compile (STOW) all objects which use that copycode. Attention:
Copycode cannot be executed on its own. It cannot be STOWed, but only SAVEd. An END statement must not be placed within a copycode.
For further information, refer to the description of the INCLUDE statement (in the Statements documentation).
60
Programming Guide
11
61
Documenting Natural Objects - Text The Natural object type text is used to write text rather than programs.
Writing Text
You write the text using the Natural program editor. The only difference in handling as opposed to writing programs is that there is no lower to upper case translation, that is, the text you write stays as it is. You can remove empty lines by setting the editor profile option Empty Line Suppression for Text to Y. See also Editor Defaults and General Defaults in the Editors documentation. You can write any text you wish (there is no syntax check). Text objects can only be saved (SAVE), they cannot be stowed (STOW). They cannot be executed (RUN), only displayed in the editor.
62
Programming Guide
12
Classes are used to apply an object based programming style. For more information, refer to the NaturalX section of the Programming Guide.
63
64
13
What are Resources? ....................................................................................................................... 66 Use of Resources ............................................................................................................................ 66 API for Processing Resources ........................................................................................................... 67
65
Using Non-Natural Files - Resource This section describes the Natural object of type resource. Note: In contrast to Natural for Open Systems, where shared and private resources are available, currently only shared resources are available in Natural for Mainframes.
Use of Resources
Objects of type resource are used by the XML Toolkit as containers for DTDs, XML schemas, style sheets, etc. The Natural Web Interface makes use of resources, such as GIFs or JPEGs. In addition, objects of type resource can be used to store XLIFF translation files. The following topics are covered below:
66
Programming Guide
Using Non-Natural Files - Resource Resource Long Name A resource long name is stored in the third directory records of the resource using the follwing structure:
Bytes 1-2 3-6 7 Format Content B2 A4 A1 Line number H'0000' Resource type, usually the extension of the resource name Resource format, where A = alphanumeric, B = binary, U = Unicode
The long name of a resource can be displayed using the system command LIST. It is shown in the List of Objects when you issue the function code LN.
Storage of Resources
Objects of type resource are stored in libraries in the same way as the other Natural programming object sources. They can be handled with the utilities SYSMAIN and INPL and with the Object Handler. They cannot be edited with the Natural editors.
Programming Guide
67
68
14
Defining Fields
This part describes how you define the fields you wish to use in a program. These fields can be database fields and user-defined fields.
Use and Structure of DEFINE DATA Statement User-Defined Variables Introduction to Dynamic Variables and Fields Using Dynamic and Large Variables User-Defined Constants Initial Values (and the RESET Statement) Redefining Fields Arrays X-Arrays
Please note that only the major options of the DEFINE DATA statement are discussed here. Further options are described in the Statements documentation. The particulars of database fields are described in Accessing Data in an Adabas Database. On principle, the features and examples described there for Adabas also apply to other database management systems. Differences, if any, are described in the relevant database interface documentation and in the Statements documentation or Parameter Reference.
69
70
15
Field Definitions in DEFINE DATA Statement ........................................................................................ 72 Defining Fields within a DEFINE DATA Statement .................................................................................. 72 Defining Fields in a Separate Data Area ............................................................................................... 73 Structuring a DEFINE DATA Statement Using Level Numbers .................................................................. 73 Storage Alignment ........................................................................................................................... 76
71
Use and Structure of DEFINE DATA Statement The first statement in a Natural program written in structured mode must always be a DEFINE DATA statement which is used to define fields for use in a program. For information on structural indentation of a source program, see the Natural system command STRUCT.
The fields can be defined within the DEFINE DATA statement itself (see below). The fields can be defined outside the program in a local or global data area, with the DEFINE DATA statement referencing that data area (see below).
If fields are used by multiple programs/routines, they should be defined in a data area outside the programs. For a clear application structure, it is usually better to define fields in data areas outside the programs. Data areas are created and maintained with the data area editor, which is described in the Editors documentation. In the first example below, the fields are defined within the DEFINE DATA statement of the program. In the second example, the same fields are defined in a local data area (LDA), and the DEFINE DATA statement only contains a reference to that data area.
DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 PERSONNEL-ID 1 #VARI-A (A20) 1 #VARI-B (N3.2) 1 #VARI-C (I4)
72
Programming Guide
I T L - - V 1 2 2 2 1 1 1
Structuring and Grouping Your Definitions Level Numbers in View Definitions Level Numbers in Field Groups
Programming Guide
73
Level numbers are 1- or 2-digit numbers in the range from 01 to 99 (the leading zero is optional). Generally, variable definitions are on Level 1. The level numbering in view definitions, redefinitions and groups must be sequential; no level numbers may be skipped.
DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 BIRTH ... END-DEFINE
74
Programming Guide
Use and Structure of DEFINE DATA Statement Example of Level Numbers in Group:
DEFINE DATA LOCAL 1 #FIELDA (N2.2) 1 #FIELDB (I4) 1 #GROUPA 2 #FIELDC (A20) 2 #FIELDD (A10) 2 #FIELDE (N3.2) 1 #FIELDF (A2) ... END-DEFINE
In this example, the fields #FIELDC, #FIELDD and #FIELDE are defined under the common group name #GROUPA. The other three fields are not part of the group. Note that #GROUPA only serves as a group name and is not a field in its own right (and therefore does not have a format/length definition).
DEFINE DATA LOCAL 1 VIEWEMP VIEW OF STAFFDDM 2 BIRTH 2 REDEFINE BIRTH 3 #YEAR-OF-BIRTH (N4) 3 #MONTH-OF-BIRTH (N2) 3 #DAY-OF-BIRTH (N2) 1 #FIELDA (A20) 1 REDEFINE #FIELDA 2 #SUBFIELD1 (N5) 2 #SUBFIELD2 (A10) 2 #SUBFIELD3 (N5) ... END-DEFINE
In this example, the database field BIRTH is redefined as three user-defined variables, and the userdefined variable #FIELDA is redefined as three other user-defined variables.
Programming Guide
75
Storage Alignment
The storage area, in which all user-defined variables are stored, always begins on a double-word boundary. If a DEFINE DATA statement is used, all data blocks (for example, LOCAL, GLOBAL blocks) are doubleword aligned, and all hierarchical structures (view definitions and groups) on Level 1 are fullword aligned. Redefinitions, scalar and array variables are not aligned, even if they are defined at level 1. Alignment within the data area is the responsibility of the user and is governed by the order in which variables are defined to Natural.
76
Programming Guide
16
User-Defined Variables
Definition of Variables ....................................................................................................................... 78 Referencing of Database Fields Using (r) Notation ................................................................................. 79 Renumbering of Source-Code Line Number References ......................................................................... 80 Format and Length of User-Defined Variables ....................................................................................... 81 Special Formats .............................................................................................................................. 83 Index Notation ................................................................................................................................ 85 Referencing a Database Array ........................................................................................................... 88 Referencing the Internal Count for a Database Array (C* Notation) ............................................................ 95 Qualifying Data Structures ................................................................................................................ 99 Examples of User-Defined Variables .................................................................................................. 100
77
User-Defined Variables User-defined variables are fields which you define yourself in a program. They are used to store values or intermediate results obtained at some point in program processing for additional processing or display. See also Naming Conventions for User-Defined Variables in Using Natural.
Definition of Variables
You define a user-defined variable by specifying its name and its format/length in the DEFINE DATA statement. You define the characteristics of a variable with the following notation:
(r,format-length/index)
This notation follows the variable name, optionally separated by one or more blanks. No blanks are allowed between the individual elements of the notation. The individual elements may be specified selectively as required, but when used together, they must be separated by the characters as indicated above. Example: In this example, a user-defined variable of alphanumeric format and a length of 10 positions is defined with the name #FIELD1.
Notes: 1. If operating in structured mode or if a program contains a DEFINE DATA LOCAL clause, variables cannot be defined dynamically in a statement. 2. This does not apply to application-independent variables (AIVs); see also Defining ApplicationIndependent Variables
78
Programming Guide
User-Defined Variables
Default Referencing of Database Fields Referencing with Statement Labels Referencing with Source-Code Line Numbers
By default, the innermost active database loop (FIND, READ or HISTOGRAM) in which the database field in question has been read is referenced. If the field is not read in any active database loop, the last previous GET statement (in reporting mode also FIND FIRST or FIND UNIQUE statement) is referenced which is not contained in an already closed loop and which has read the field.
... RD. READ PERSON-VIEW BY NAME STARTING FROM 'JONES' FD. FIND AUTO-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (FD.) DISPLAY NAME (RD.) FIRST-NAME (RD.) MAKE (FD.) END-FIND END-READ ...
Programming Guide
79
User-Defined Variables
... 0110 FIND EMPLOYEES-VIEW WITH NAME = 'SMITH' 0120 FIND VEHICLES-VIEW WITH MODEL = 'FORD' 0130 DISPLAY NAME (0110) MODEL (0120) 0140 END-FIND 0150 END-FIND ...
Sample Statement
ESCAPE BOTTOM (0150)
If the left parenthesis or the four-digit number nnnn is followed by a blank, or the four-digit number nnnn is followed by a period, the pattern is not considered to be a valid source code line number reference. To avoid that a four-digit number that is contained in an alphanumeric constant is unintentionally renumbered, the constant should be split up and the different parts should be concatenated to form a single value by use of a hyphen.
80
Programming Guide
should be replaced by
Z := 'XXXX (1234' - ',00) YYYY'
Numeric (unpacked) 1 - 29
Length can only be specified if format is specified. With some formats, the length need not be explicitly specified (as shown in the table above). For fields defined with format N or P, you can use decimal position notation in the form nn.m. nn represents the number of positions before the decimal point, and m represents the number of positions after the decimal point. The sum of the values of nn and m must not exceed 29 and the value of m must not exceed 7. The maximum Definable Length (1 GB for alphanumeric, binary and Unicode fields) represents the limit which is imposed by the Natural compiler. In reality, however, the amount of memory that can be obtained as data storage is very much smaller. Especially if running in a Natural thread based environment, the size of the session dependent user areas, hence the extent of the
Programming Guide
81
User-Defined Variables user fields in the data area is restricted to the value defined with the keyword parameter MAXSIZE in the macro NTSWPRM. Notes: 1. When a user-defined variable of format P is output with a DISPLAY, WRITE, or INPUT statement, Natural internally converts the format to N for the output. 2. In reporting mode, if format and length are not specified for a user-defined variable, the default format/length N7 will be used, unless this default assignment has been disabled by the profile/session parameter FS. For a database field, the format/length as defined for the field in the DDM apply. (In reporting mode, it is also possible to define in a program a different format/length for a database field.) In structured mode, format and length may only be specified in a data area definition or with a DEFINE DATA statement. Example of Format/Length Definition - Structured Mode:
DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 1 #NEW-SALARY (N6.2) END-DEFINE ... FIND EMPLOY-VIEW ... ... COMPUTE #NEW-SALARY = ... ...
In reporting mode, format/length may be defined within the body of the program, if no DEFINE DATA statement is used. Example of Format/Length Definition - Reporting Mode:
... ... FIND EMPLOYEES ... ... COMPUTE #NEW-SALARY(N6.2) = ... ...
82
Programming Guide
User-Defined Variables
Special Formats
In addition to the standard alphanumeric (A) and numeric (B, F, I, N, P) formats, Natural supports the following special formats:
Format C - Attribute Control Formats D - Date, and T - Time Format L - Logical Format: Handle
Programming Guide
83
DEFINE DATA LOCAL 1 #DAT1 (D) END-DEFINE * MOVE *DATX TO #DAT1 ADD 7 TO #DAT1 WRITE '=' #DAT1 END
For further information, see the session parameter EM and the system variables *DATX and *TIMX. The value in a date field must be in the range from 1st January 1582 to 31st December 2699.
Format L - Logical
A variable defined with format L may be used as a logical condition criterion. It can take the value TRUE or FALSE. For a variable of format L, no length can be specified. A variable of format L is always assigned a length of 1 byte by Natural. Example:
DEFINE DATA LOCAL 1 #SWITCH(L) END-DEFINE MOVE TRUE TO #SWITCH ... IF #SWITCH ... MOVE FALSE TO #SWITCH ELSE ... MOVE TRUE TO #SWITCH END-IF
For further information on logical value presentation, see the session parameter EM.
84
Programming Guide
User-Defined Variables
Format: Handle
A variable defined as HANDLE OF OBJECT can be used as an object handle. For further information on object handles, see the section NaturalX.
Index Notation
An index notation is used for fields that represent an array. An integer numeric constant or user-defined variable may be used in index notations. A userdefined variable can be specified using one of the following formats: N (numeric), P (packed), I (integer) or B (binary), where format B may be used only with a length of less than or equal to 4. A system variable, system function or qualified variable cannot be used in index notations. Array Definition - Examples: 1. #ARRAY (3) Defines a one-dimensional array with three occurrences. 2. FIELD ( label.,A20/5) orlabel.FIELD(A20/5) Defines an array from a database field referencing the statement marked by label. with format alphanumeric, length 20 and 5 occurrences. 3. #ARRAY (N7.2/1:5,10:12,1:4) Defines an array with format/length N7.2 and three array dimensions with 5 occurrences in the first, 3 occurrences in the second and 4 occurrences in the third dimension. 4. FIELD ( label./i:i + 5) orlabel.FIELD(i:i + 5) Defines an array from a database field referencing the statement marked by label..
FIELD represents a multiple-value field or a field from a periodic group where i specifies the
offset index within the database occurrence. The size of the array within the program is defined as 6 occurrences (i:i + 5). The database offset index is specified as a variable to allow for the positioning of the program array within the occurrences of the multiple-value field or periodic group. For any repositioning of i a new access must be made to the database via a GET or GET SAME statement. Natural allows for the definition of arrays where the index does not have to begin with 1. At runtime, Natural checks that index values specified in the reference do not exceed the maximum size of dimensions as specified in the definition. Notes: 1. For compatibility with earlier Natural versions, an array range may be specified using a hyphen (-) instead of a colon (:). Programming Guide 85
User-Defined Variables 2. A mix of both notations, however, is not permitted. 3. The hyphen notation is only allowed in reporting mode (but not in a DEFINE DATA statement). The maximum index value is 1,073,741,824. The maximum size of a data area per programming object is 1,073,741,824 bytes (1 GB). Caution: For Compatibility with Natural Version 4.1 on Mainframes: Use the V41COMP compilation option of the CMPO profile parameter or NTCMPO macro to reduce these limits for compatibility reasons to the limits applicable for Natural Version 4.1 on mainframe computers. Simple arithmetic expressions using the plus (+) and minus (-) operators may be used in index references. When arithmetic expressions are used as indices, these operators must be preceded and followed by a blank. Arrays in group structures are resolved by Natural field by field, not group occurrence by group occurrence. Example of Group Array Resolution:
DEFINE DATA LOCAL 1 #GROUP (1:2) 2 #FIELDA (A5/1:2) 2 #FIELDB (A5) END-DEFINE ...
and not:
#FIELDA(1,1) #FIELDA(1,2) #FIELDB(1) #FIELDA(2,1) #FIELDA(2,2) #FIELDB(2)
86
Programming Guide
User-Defined Variables Array Referencing - Examples: 1. #ARRAY (1) References the first occurrence of a one-dimensional array. 2. #ARRAY (7:12) References the seventh to twelfth occurrence of a one-dimensional array. 3. #ARRAY (i + 5) References the i+fifth occurrence of a one-dimensional array. 4. #ARRAY (5,3:7,1:4) Reference is made within a three dimensional array to occurrence 5 in the first dimension, occurrences 3 to 7 (5 occurrences) in the second dimension and 1 to 4 (4 occurrences) in the third dimension. 5. An asterisk may be used to reference all occurrences within a dimension:
DEFINE DATA LOCAL 1 #ARRAY1 (N5/1:4,1:4) 1 #ARRAY2 (N5/1:4,1:4) END-DEFINE ... ADD #ARRAY1 (2,*) TO #ARRAY2 (4,*) ...
not:
#ARRAY(1000)
because the latter would be interpreted as a reference to source code line 1000.
Programming Guide
87
User-Defined Variables If an index variable name could be misinterpreted as a format/length specification, a slash (/) must be used to indicate that an index is being specified. If, for example, the occurrence of an array is defined by the value of the variable N7, the occurrence must be specified as:
#ARRAY (/N7)
not:
#ARRAY (N7)
because the latter would be misinterpreted as the definition of a 7-byte numeric field.
Referencing Multiple-Value Fields and Periodic-Group Fields Referencing Arrays Defined with Constants Referencing Arrays Defined with Variables Referencing Multiple-Defined Arrays
Note: Before executing the following example programs, please run the program INDEXTST in the library SYSEXPG to create an example record that uses 10 different language codes.
DEFINE DATA LOCAL 1 I (I2) 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 LANG (1:10) 2 LANG (I:I+10) END-DEFINE
88
Programming Guide
Notes: 1. The same lower bound index may only be used once per array, (this applies to constant indexes as well as variable indexes). 2. For an array definition using a variable index, the lower bound must be specified using the variable by itself, and the upper bound must be specified using the same variable plus a constant.
** Example 'INDEX1R': Array definition with constants (reporting mode) *********************************************************************** * READ (1) EMPLOYEES WITH NAME = 'WINTER' WHERE CITY = 'LONDON' OBTAIN LANG (1:10) /* WRITE 'LANG(1:10):' LANG (1:10) // WRITE 'LANG(1) :' LANG (1) / 'LANG(5:9) :' LANG (5:9) LOOP * END
** Example 'INDEX1S': Array definition with constants (structured mode) *********************************************************************** DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 LANG (1:10) END-DEFINE
Programming Guide
89
User-Defined Variables
* READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' WRITE 'LANG(1:10):' LANG (1:10) // WRITE 'LANG(1) :' LANG (1) / 'LANG(5:9) :' LANG (5:9) END-READ END
If a multiple-value field or periodic-group field is defined several times using constants and is to be referenced using variables, the following syntax is used. Reporting Mode Example:
** Example 'INDEX2R': Array definition with constants (reporting mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (1:5) 2 LANG (4:8) END-DEFINE * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' DISPLAY 'NAME' NAME 'LANGUAGE/1:3' LANG (1.1:3) 'LANGUAGE/6:8' LANG (4.3:5) LOOP * END
** Example 'INDEX2S': Array definition with constants (structured mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (1:5) 2 LANG (4:8) END-DEFINE * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' DISPLAY 'NAME' NAME 'LANGUAGE/1:3' LANG (1.1:3) 'LANGUAGE/6:8' LANG (4.3:5) END-READ
90
Programming Guide
User-Defined Variables
* END
** Example 'INDEX3R': Array definition with variables (reporting mode) *********************************************************************** RESET I (I2) * I := 1 READ (1) EMPLOYEES WITH NAME = 'WINTER' WHERE CITY = 'LONDON' OBTAIN LANG (I:I+10) /* WRITE 'LANG(I) :' LANG (I) / 'LANG(I+5:I+7):' LANG (I+5:I+7) LOOP * END
** Example 'INDEX3S': Array definition with variables (structured mode) *********************************************************************** DEFINE DATA LOCAL 1 I (I2) * 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (I:I+10) END-DEFINE * I := 1 READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' WRITE 'LANG(I) :' LANG (I) / 'LANG(I+5:I+7):' LANG (I+5:I+7) END-READ END
If a different index is to be used, an unambiguous reference to the first encountered definition of the array with variable index must be made. This is done by qualifying the index expression as shown below.
Programming Guide
91
** Example 'INDEX4R': Array definition with variables (reporting mode) *********************************************************************** RESET I (I2) J (I2) * I := 2 J := 3 * READ (1) EMPLOYEES WITH NAME = 'WINTER' WHERE CITY = 'LONDON' OBTAIN LANG (I:I+10) /* WRITE 'LANG(I.J) :' LANG (I.J) / 'LANG(I.1:5):' LANG (I.1:5) LOOP * END
** Example 'INDEX4S': Array definition with variables (structured mode) *********************************************************************** DEFINE DATA LOCAL 1 I (I2) 1 J (I2) 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (I:I+10) END-DEFINE * I := 2 J := 3 READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' WRITE 'LANG(I.J) :' LANG (I.J) / 'LANG(I.1:5):' LANG (I.1:5) END-READ END
The expression I. is used to create an unambiguous reference to the array definition and positions to the first value within the read array range (LANG(I.1:5)). The current content of I at the time of the database access determines the starting occurrence of the database array.
92
Programming Guide
User-Defined Variables
** Example 'INDEX5R': Array definition with constants (reporting mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL /* For reporting mode programs 1 EMPLOY-VIEW VIEW OF EMPLOYEES /* DEFINE DATA is recommended 2 NAME /* to use multiple definitions 2 CITY /* of same database field 2 LANG (1:10) 2 LANG (5:10) * 1 I (I2) 1 J (I2) END-DEFINE * I := 1 J := 2 * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' WRITE 'LANG(1.1:10) :' LANG (1.1:10) / 'LANG(1.I:I+2):' LANG (1.I:I+2) // WRITE 'LANG(5.1:5) :' LANG (5.1:5) / 'LANG(5.J) :' LANG (5.J) LOOP END
** Example 'INDEX5S': Array definition with constants (structured mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (1:10) 2 LANG (5:10) * 1 I (I2) 1 J (I2) END-DEFINE * *
Programming Guide
93
User-Defined Variables
I := 1 J := 2 * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' WRITE 'LANG(1.1:10) :' LANG (1.1:10) / 'LANG(1.I:I+2):' LANG (1.I:I+2) // WRITE 'LANG(5.1:5) :' LANG (5.1:5) / 'LANG(5.J) :' LANG (5.J) END-READ END
A similar syntax is also used if multiple-value fields or periodic-group fields are defined using index variables. Reporting Mode Example:
** Example 'INDEX6R': Array definition with variables (reporting mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL 1 I (I2) INIT <1> 1 J (I2) INIT <2> 1 N (I2) INIT <1> 1 EMPLOY-VIEW VIEW OF EMPLOYEES /* For reporting mode programs 2 NAME /* DEFINE DATA is recommended 2 CITY /* to use multiple definitions 2 LANG (I:I+10) /* of same database field 2 LANG (J:J+5) 2 LANG (4:5) * END-DEFINE * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' * WRITE 'LANG(I.I) :' LANG (I.I) / 'LANG(1.I:I+2):' LANG (I.I:I+10) // * WRITE 'LANG(J.N) :' LANG (J.N) / 'LANG(J.2:4) :' LANG (J.2:4) // * WRITE 'LANG(4.N) :' LANG (4.N) / 'LANG(4.N:N+1):' LANG (4.N:N+1) / LOOP END
94
Programming Guide
** Example 'INDEX6S': Array definition with variables (structured mode) ** (multiple definition of same database field) *********************************************************************** DEFINE DATA LOCAL 1 I (I2) INIT <1> 1 J (I2) INIT <2> 1 N (I2) INIT <1> 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 LANG (I:I+10) 2 LANG (J:J+5) 2 LANG (4:5) * END-DEFINE * READ (1) EMPLOY-VIEW WITH NAME = 'WINTER' WHERE CITY = 'LONDON' * WRITE 'LANG(I.I) :' LANG (I.I) / 'LANG(1.I:I+2):' LANG (I.I:I+10) // * WRITE 'LANG(J.N) :' LANG (J.N) / 'LANG(J.2:4) :' LANG (J.2:4) // * WRITE 'LANG(4.N) :' LANG (4.N) / 'LANG(4.N:N+1):' LANG (4.N:N+1) / END-READ END
Programming Guide
95
VSAM With VSAM and DL/I databases, the C* notation does not return the number of values/occurrences DL/I but the maximum occurrence/value as defined in the DDM (MAXOCC).
See also the data-area-editor line command .* (in the Editors documentation). The explicit format and length permitted to declare a C* field is either
integer (I) with a length of 2 bytes (I2) or 4 bytes (I4), numeric (N) or packed (P) with only integer (but no precision) digits; for example (N3).
If no explicit format and length is supplied, format/length (N3) is assumed as default. Examples:
C*LANG C*INCOME
Returns the count of the number of values for the multiple-value field LANG. Returns the count of the number of occurrences for the periodic group INCOME.
C*BONUS(1) Returns the count of the number of values for the multiple-value field BONUS in periodic group occurrence 1 (assuming that BONUS is a multiple-value field within a periodic group.)
** Example 'CNOTX01': C* Notation ************************************************************************ DEFINE DATA LOCAL 1 EMPL-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 C*INCOME 2 INCOME 3 SALARY (1:5) 3 C*BONUS (1:2) 3 BONUS (1:2,1:2) 2 C*LANG 2 LANG (1:2) * 1 #I (N1) END-DEFINE * LIMIT 2 READ EMPL-VIEW BY CITY /* WRITE NOTITLE 'NAME:' NAME / 'NUMBER OF LANGUAGES SPOKEN:' C*LANG 5X
96
Programming Guide
User-Defined Variables
'LANGUAGE 1:' LANG (1) 5X 'LANGUAGE 2:' LANG (2) /* WRITE 'SALARY DATA:' FOR #I FROM 1 TO C*INCOME WRITE 'SALARY' #I SALARY (1.#I) END-FOR /* WRITE 'THIS YEAR BONUS:' C*BONUS(1) / 'LAST YEAR BONUS:' C*BONUS(2) SKIP 1 END-READ END
NAME: SENKO NUMBER OF LANGUAGES SPOKEN: SALARY DATA: SALARY 1 36225 SALARY 2 29900 SALARY 3 28100 SALARY 4 26600 SALARY 5 25200 THIS YEAR BONUS: 0 LAST YEAR BONUS: 0
LANGUAGE 1: ENG
LANGUAGE 2:
0 0
0 0
NAME: CANALE NUMBER OF LANGUAGES SPOKEN: 2 SALARY DATA: SALARY 1 202285 THIS YEAR BONUS: 1 23000 LAST YEAR BONUS: 0 0
LANGUAGE 1: FRE
LANGUAGE 2: ENG
0 0
Programming Guide
97
** Example 'CNOTX02': C* Notation (multiple-value fields) ************************************************************************ * LIMIT 2 READ EMPLOYEES BY CITY OBTAIN C*BONUS (1:3) BONUS (1:3,1:3) /* DISPLAY NAME C*BONUS (1:3) BONUS (1:3,1:3) LOOP * END
** Example 'CNOTX03': C* Notation (multiple-value fields) ************************************************************************ DEFINE DATA LOCAL 1 EMPL-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 INCOME (1:3) 3 C*BONUS 3 BONUS (1:3) END-DEFINE * LIMIT 2 READ EMPL-VIEW BY CITY /* DISPLAY NAME C*BONUS (1:3) BONUS (1:3,1:3) END-READ * END
** Example 'CNOTX04': C* Notation (multiple-value fields) ************************************************************************ DEFINE DATA LOCAL 1 EMPL-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 C*BONUS (1:3) 2 INCOME (1:3) 3 BONUS (1:3) END-DEFINE
98
Programming Guide
User-Defined Variables
* LIMIT 2 READ EMPL-VIEW BY CITY /* DISPLAY NAME C*BONUS (*) BONUS (*,*) END-READ * END
Caution: As the Adabas format buffer does not permit ranges for count fields, they are generated as individual fields; therefore a C* index range for a large array may cause an Adabas format buffer overflow.
DEFINE DATA LOCAL 1 FULL-NAME 2 LAST-NAME (A20) 2 FIRST-NAME (A15) 1 OUTPUT-NAME 2 LAST-NAME (A20) 2 FIRST-NAME (A15) END-DEFINE ... MOVE FULL-NAME.LAST-NAME TO OUTPUT-NAME.LAST-NAME ...
Programming Guide
99
DEFINE DATA LOCAL 1 GROUP1 2 SUB-GROUP 3 FIELD1 (A15) 3 FIELD2 (A15) END-DEFINE ... MOVE 'ABC' TO GROUP1.FIELD1 ...
Qualifying a Database Field: If you use the same name for a user-defined variable and a database field (which you should not do anyway), you must qualify the database field when you want to reference it Caution: If you do not qualify the database field when you want to reference it, the userdefined variable will be referenced instead.
/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*
Alphanumeric, 10 positions. Binary, 4 positions. Packed numeric, 4 positions and 1 sign position. Unpacked numeric, 7 positions before and 2 after decimal point. Invalid definition!!! Packed numeric, 7 positions before and 2 after decimal point and 1 sign position. Integer, 1 byte. Integer, 2 bytes. Invalid definition!!! Integer, 4 bytes. Invalid definition!!! Floating point, 4 bytes. Floating point, 8 bytes. Invalid definition!!! Date (internal format/length P6). Time (internal format/length P12). Logical, 1 byte (TRUE or FALSE).
END-DEFINE
100
Programming Guide
17
Purpose of Dynamic Variables .......................................................................................................... 102 Definition of Dynamic Variables ........................................................................................................ 102 Value Space Currently Used for a Dynamic Variable ............................................................................. 103 Allocating/Freeing Memory Space for a Dynamic Variable ...................................................................... 103
101
102
Programming Guide
Introduction to Dynamic Variables and Fields Dynamic variables can only be defined in a DEFINE DATA statement using the following syntax:
level variable-name ( A ) DYNAMIC level variable-name ( B ) DYNAMIC level variable-name ( U ) DYNAMIC
A redefinition of a dynamic variable is not allowed. A dynamic variable may not be contained in a REDEFINE clause.
variable. For A and B format, the size of one code unit is 1 byte. For U format, the size of one code unit is 2 bytes (UTF-16). *LENGTH may be used only to get the currently used length for dynamic variables.
Programming Guide
103
- where operand1 is a dynamic variable and operand2 is a non-negative numeric size value.
EXPAND
Function The EXPAND statement is used to increase the allocated length of the dynamic variable (operand1) to the specified length (operand2). Changing the Specified Size The length currently used (as indicated by the Natural system variable *LENGTH, see above) for the dynamic variable is not modified. If the specified length (operand2) is less than the allocated length of the dynamic variable, the statement will be ignored.
REDUCE
Function The REDUCE statement is used to reduce the allocated length of the dynamic variable (operand1) to the specified length (operand2). The storage allocated for the dynamic variable (operand1) beyond the specified length (operand2) may be released at any time, when the statement is executed or at a later time. Changing the Specified Length If the length currently used (as indicated by the Natural system variable *LENGTH, see above) for the dynamic variable is greater than the specified length (operand2), *LENGTH of this dynamic variable is set to the specified length. The content of the variable is truncated, but not modified. If the given length is larger than the currently allocated storage of the dynamic variable, the statement will be ignored.
104
Programming Guide
RESIZE
Function The RESIZE statement adjusts the currently allocated length of the dynamic variable (operand1) to the specified length (operand2). Changing the Specified Length If the specified length is smaller then the used length (as indicated by the Natural system variable *LENGTH, see above) of the dynamic variable, the used length is reduced accordingly. If the specified length is larger than the currently allocated length of the dynamic variable, the allocated length of the dynamic variable is increased. The currently used length (as indicated by *LENGTH) of the dynamic variable is not affected and remains unchanged. If the specified length is the same as the currently allocated length of the dynamic variable, the execution of the RESIZE statement has no effect.
Programming Guide
105
106
18
General Remarks .......................................................................................................................... 108 Assignments with Dynamic Variables ................................................................................................. 109 Initialization of Dynamic Variables ..................................................................................................... 111 String Manipulation with Dynamic Alphanumeric Variables ..................................................................... 111 Logical Condition Criterion (LCC) with Dynamic Variables ...................................................................... 113 AT/IF-BREAK of Dynamic Control Fields ............................................................................................ 114 Parameter Transfer with Dynamic Variables ........................................................................................ 115 Work File Access with Large and Dynamic Variables ............................................................................. 118 Performance Aspects with Dynamic Variables ..................................................................................... 118 Outputting Dynamic Variables .......................................................................................................... 119 Dynamic X-Arrays .......................................................................................................................... 120
107
General Remarks
Generally, the following rules apply:
A dynamic alphanumeric field may be used wherever an alphanumeric field is allowed. A dynamic binary field may be used wherever a binary field is allowed. A dynamic Unicode field may be used wherever a Unicode field is allowed.
Exception: Dynamic variables are not allowed within the SORT statement. To use dynamic variables in a DISPLAY, WRITE, PRINT, REINPUT or INPUT statement, you must use either the session parameter AL or EM to define the length of the variable. The used length (as indicated by the Natural system variable *LENGTH, see Value Space Currently Used for a Dynamic Variable) and the size of the allocated storage of dynamic variables are equal to zero until the variable is accessed as a target operand for the first time. Due to assignments or other manipulation operations, dynamic variables may be firstly allocated or extended (reallocated) to the exact size of the source operand. The size of a dynamic variable may be extended if it is used as a modifiable operand (target operand) in the following statements:
ASSIGN CALLNAT COMPRESS EXAMINE MOVE PERFORM operand1 (destination operand in an assignment).
See Parameter Transfer with Dynamic Variables (except if AD=O, or if BY VALUE exists in the corresponding parameter data area).
operand2, see Processing. operand1 in the DELETE REPLACE clause. operand2 (destination operand), see Function.
READ WORK FILE operand1 and operand2, see Handling of Large and Dynamic Variables. SEPARATE SELECT (SQL) SEND METHOD
108
Programming Guide
Using Dynamic and Large Variables Currently, there is the following limit concerning the usage of large variables:
CALL Parameter size less than 64 KB per parameter (no limit for the CALL with INTERFACE4 option).
In the following sections, the use of dynamic variables is discussed in more detail with examples.
#MYDYNTEXT1 := OPERAND MOVE OPERAND TO #MYDYNTEXT1 /* #MYDYNTEXT1 IS AUTOMATICALLY EXTENDED UNTIL THE SOURCE OPERAND CAN BE COPIED MOVE ALL, MOVE ALL UNTIL with dynamic target operands are defined as follows:
MOVE ALL
moves the source operand repeatedly to the target operand until the used length (*LENGTH) of the target operand is reached. *LENGTH is not modified. If *LENGTH is zero, the statement will be ignored. moves operand1 repeatedly to operand2 until the length specified in operand3 is reached. If operand3 is greater than *LENGTH(operand2), operand2 is extended and *LENGTH( operand2) is set to operand3. If operand3 is less than *LENGTH(operand2), the used length is reduced to operand3. If operand3 equals *LENGTH(operand2), the behavior is equivalent to MOVE ALL.
Example:
#MYDYNTEXT1 := 'ABCDEFGHIJKLMNO' MOVE ALL 'AB' TO #MYDYNTEXT1 'ABABABABABABABA'; MOVE ALL 'CD' TO #MYDYNTEXT1 UNTIL 6 MOVE ALL 'EF' TO #MYDYNTEXT1 UNTIL 10
/* *LENGTH(#MYDYNTEXT1) = 15 /* CONTENT OF #MYDYNTEXT1 = /* *LENGTH IS STILL 15 /* CONTENT OF #MYDYNTEXT1 = 'CDCDCD'; /* *LENGTH = 6 /* CONTENT OF #MYDYNTEXT1 = 'EFEFEFEFEF'; /* *LENGTH = 10
MOVE JUSTIFIED is rejected at compile time if the target operand is a dynamic variable.
Programming Guide
109
string behind the used length of a dynamic variable (*LENGTH) is referenced. MOVE TO SUBSTR will lead to a runtime error if a sub-string position behind *LENGTH + 1 is referenced, because this would lead to an undefined gap in the content of the dynamic variable. If the target operand should be extended by MOVE TO SUBSTR (for example if the second operand is set to *LENGTH+1), the third operand is mandatory. Valid syntax:
#OP2 := *LENGTH(#MYDYNTEXT1) MOVE SUBSTR (#MYDYNTEXT1, #OP2) TO OPERAND TO OPERAND #OP2 := *LENGTH(#MYDYNTEXT1) + 1 MOVE OPERAND TO SUBSTR(#MYDYNTEXT1, #OP2, #lEN_OPERAND) TO #MYDYNTEXT1
/* CONCATENATE OPERAND
Invalid syntax:
#OP2 := *LENGTH(#MYDYNTEXT1) + 1 MOVE SUBSTR (#MYDYNTEXT1, #OP2, 10) TO OPERAND UNDEFINED SUB-STRING #OP2 := *LENGTH(#MYDYNTEXT1 + 10) MOVE OPERAND TO SUBSTR(#MYDYNTEXT1, #OP2, #EN_OPERAND) UNDEFINED GAP #OP2 := *LENGTH(#MYDYNTEXT1) + 1 MOVE OPERAND TO SUBSTR(#MYDYNTEXT1, #OP2) UNDEFINED LENGTH
If the source operand is a static variable, the used length of the dynamic destination operand (*LENGTH(#MYDYNTEXT1)) is set to the format length of the static variable and the source value is copied in this length including trailing blanks (alphanumeric and Unicode fields) or binary zeros (for binary fields). If the destination operand is static and the source operand is dynamic, the dynamic variable is copied in its currently used length. If this length is less than the format length of the static variable, the remainder is filled with blanks (for alphanumeric and Unicode fields) or binary zeros (for binary fields). Otherwise, the value will be truncated. If the currently used length of the dynamic
110
Programming Guide
Using Dynamic and Large Variables variable is 0, the static target operand is filled with blanks (for alphanumeric and Unicode fields) or binary zeros (for binary fields).
DEFINE DATA LOCAL 1 #MYDYNTEXT1 (A) DYNAMIC END-DEFINE #MYDYNTEXT1 := 'SHORT TEXT' WRITE *LENGTH(#MYDYNTEXT1) RESET #MYDYNTEXT1
To initialize a dynamic variable with a specified value in a specified size, the MOVE ALL UNTIL statement may be used. Example:
Programming Guide
111
** Example 'DYNAMX01': Dynamic variables (with COMPRESS and SEPARATE) ************************************************************************ DEFINE DATA LOCAL 1 #MYDYNTEXT1 (A) DYNAMIC 1 #TEXT (A20) 1 #DYN1 (A) DYNAMIC 1 #DYN2 (A) DYNAMIC 1 #DYN3 (A) DYNAMIC END-DEFINE * MOVE ' HELLO WORLD ' TO #MYDYNTEXT1 WRITE #MYDYNTEXT1 (AL=25) 'with length' *LENGTH (#MYDYNTEXT1) /* dynamic variable with leading and trailing blanks * MOVE ' HELLO WORLD ' TO #TEXT * MOVE #TEXT TO #MYDYNTEXT1 WRITE #MYDYNTEXT1 (AL=25) 'with length' *LENGTH (#MYDYNTEXT1) /* dynamic variable with whole variable length of #TEXT * COMPRESS #TEXT INTO #MYDYNTEXT1 WRITE #MYDYNTEXT1 (AL=25) 'with length' *LENGTH (#MYDYNTEXT1) /* dynamic variable with leading blanks of #TEXT * * #MYDYNTEXT1 := 'HERE COMES THE SUN' SEPARATE #MYDYNTEXT1 INTO #DYN1 #DYN2 #DYN3 IGNORE * WRITE / #MYDYNTEXT1 (AL=25) 'with length' *LENGTH (#MYDYNTEXT1) WRITE #DYN1 (AL=25) 'with length' *LENGTH (#DYN1) WRITE #DYN2 (AL=25) 'with length' *LENGTH (#DYN2) WRITE #DYN3 (AL=25) 'with length' *LENGTH (#DYN3) /* #DYN1, #DYN2, #DYN3 are automatically extended or reduced * EXAMINE #MYDYNTEXT1 FOR 'SUN' REPLACE 'MOON' WRITE / #MYDYNTEXT1 (AL=25) 'with length' *LENGTH (#MYDYNTEXT1) /* #MYDYNTEXT1 is automatically extended or reduced * END
112
Programming Guide
IF IF IF
= < >
OR OR OR
Trailing blanks for alphanumeric and Unicode variables or leading binary zeros for binary variables are processed in the same way for static and dynamic variables. For example, alphanumeric variables containing the values AA and AA followed by a blank will be considered being equal, and binary variables containing the values H0000031 and H3031 will be considered being equal. If a comparison result should only be TRUE in case of an exact copy, the used lengths of the dynamic variables have to be compared in addition. If one variable is an exact copy of the other, their used lengths are also equal. Example:
#MYDYNTEXT1 := 'HELLO' #MYDYNTEXT2 := 'HELLO ' IF #MYDYNTEXT1 = #MYDYNTEXT2 THEN ... IF #MYDYNTEXT1 = #MYDYNTEXT2 AND *LENGTH(#MYDYNTEXT1) = *LENGTH(#MYDYNTEXT2)
Two dynamic variables are compared position by position (from left to right for alphanumeric variables, and right to left for binary variables) up to the minimum of their used lengths. The first position where the variables are not equal determines if the first or the second variable is greater than, less than or equal to the other. The variables are equal if they are equal up to the minimum of their used lengths and the remainder of the longer variable contains only blanks for alphanumeric dynamic variables or binary zeros for binary dynamic variables. To compare two Unicode dynamic variables, trailing blanks are removed from both values before the ICU collation algorithm is used to compare the two resulting values. See also Logical Condition Criteria in the Unicode and Code Page Support documentation.
Programming Guide
113
#MYDYNTEXT1 := 'HELLO1' #MYDYNTEXT2 := 'HELLO2' IF #MYDYNTEXT1 < #MYDYNTEXT2 THEN #MYDYNTEXT2 := 'HALLO' IF #MYDYNTEXT1 > #MYDYNTEXT2 THEN
... ...
Comparison Compatibility
Comparisons between dynamic and static variables are equivalent to comparisons between dynamic variables. The format length of the static variable is interpreted as its used length. Example:
#MYSTATTEXT1 := 'HELLO' A20 #MYDYNTEXT1 := 'HELLO' IF #MYSTATTEXT1 = #MYDYNTEXT1 IF #MYSTATTEXT1 > #MYDYNTEXT1
THEN THEN
... ...
114
Programming Guide
Note: In the case of static/dynamic or dynamic/static definitions, a value truncation may occur according to the data transfer rules of the appropriate assignments. Example 1:
** Example 'DYNAMX02': Dynamic variables (as parameters) ************************************************************************ DEFINE DATA LOCAL 1 #MYTEXT (A) DYNAMIC END-DEFINE * #MYTEXT := '123456' /* extended to 6 bytes, *LENGTH(#MYTEXT) = 6 * CALLNAT 'DYNAMX03' USING #MYTEXT *
Programming Guide
115
Subprogram DYNAMX03:
** Example 'DYNAMX03': Dynamic variables (as parameters) ************************************************************************ DEFINE DATA PARAMETER 1 #MYPARM (A) DYNAMIC BY VALUE RESULT END-DEFINE * WRITE *LENGTH(#MYPARM) /* *LENGTH(#MYPARM) = 6 #MYPARM := '1234567' /* *LENGTH(#MYPARM) = 7 #MYPARM := '12345678' /* *LENGTH(#MYPARM) = 8 EXPAND DYNAMIC VARIABLE #MYPARM TO 10 /* 10 bytes are allocated * WRITE *LENGTH(#MYPARM) /* *LENGTH(#MYPARM) = 8 * /* content of #MYPARM is moved back to #MYTEXT /* used length of #MYTEXT = 8 * END
Example 2:
** Example 'DYNAMX04': Dynamic variables (as parameters) ************************************************************************ DEFINE DATA LOCAL 1 #MYTEXT (A) DYNAMIC END-DEFINE * #MYTEXT := '123456' /* extended to 6 bytes, *LENGTH(#MYTEXT) = 6 * CALLNAT 'DYNAMX05' USING #MYTEXT * WRITE *LENGTH(#MYTEXT) /* *LENGTH(#MYTEXT) = 8 /* at least 10 bytes are /* allocated (extended in DYNAMX05) * END
116
Programming Guide
** Example 'DYNAMX05': Dynamic variables (as parameters) ************************************************************************ DEFINE DATA PARAMETER 1 #MYPARM (A) DYNAMIC END-DEFINE * WRITE *LENGTH(#MYPARM) /* *LENGTH(#MYPARM) = 6 #MYPARM := '1234567' /* *LENGTH(#MYPARM) = 7 #MYPARM := '12345678' /* *LENGTH(#MYPARM) = 8 EXPAND DYNAMIC VARIABLE #MYPARM TO 10 /* 10 bytes are allocated * WRITE *LENGTH(#MYPARM) /* *LENGTH(#MYPARM) = 8 * END
MOVE ALL ' ' TO #MYDYNTEXT1 UNTIL 10000 /* a buffer of length 10000 is allocated /* #MYDYNTEXT1 is initialized with blanks /* and *LENGTH(#MYDYNTEXT1) = 10000 CALL INTERFACE4 'MYPROG' USING #MYDYNTEXT1 WRITE *LENGTH(#MYDYNTEXT1) /* *LENGTH(#MYDYNTEXT1) may have changed in the 3GL program
For a more detailed description, refer to the CALL statement in the Statements documentation.
Programming Guide
117
** Example 'DYNAMX06': Dynamic variables (allocated memory) ************************************************************************ DEFINE DATA LOCAL 1 #MYDYNTEXT1 (A) DYNAMIC 1 #LEN (I4) END-DEFINE * #MYDYNTEXT1 := 'a' /* used length is 1, value is 'a' /* allocated size is still 1
118
Programming Guide
Rules:
Use dynamic operands where it makes sense. Use EXPAND if upper limit of memory usage is known. Use REDUCE if the dynamic operand will no longer be needed.
Because the output of the PRINT statement is unformatted, the output of dynamic variables in the PRINT statement need not be set using AL and EM parameters. In other words, these parameters may be omitted.
Programming Guide
119
Dynamic X-Arrays
A dynamic X-array may be allocated by first specifying the number of occurrences and then expanding the length of the previously allocated array occurrences. Example:
DEFINE DATA LOCAL 1 #X-ARRAY(A/1:*) DYNAMIC END-DEFINE * EXPAND ARRAY #X-ARRAY TO (1:10) #X-ARRAY(*) := 'ABC' EXPAND ARRAY #X-ARRAY TO (1:20) #X-ARRAY(11:20) := 'DEF'
120
Programming Guide
19
User-Defined Constants
Numeric Constants ........................................................................................................................ 122 Alphanumeric Constants ................................................................................................................. 123 Unicode Constants ......................................................................................................................... 124 Date and Time Constants ................................................................................................................ 127 Hexadecimal Constants .................................................................................................................. 129 Logical Constants .......................................................................................................................... 130 Floating Point Constants ................................................................................................................. 131 Attribute Constants ........................................................................................................................ 131 Handle Constants .......................................................................................................................... 132 Defining Named Constants .............................................................................................................. 132
121
User-Defined Constants Constants can be used throughout Natural programs. This document discusses the types of constants that are supported and how they are used.
Numeric Constants
The following topics are covered below:
Numeric Constants
A numeric constant may contain 1 to 29 numeric digits, a special character for decimal point notation (period or comma) and a sign. Examples:
1234 12.34
+1234 +12.34
-1234 -12.34
MOVE 3 TO #XYZ COMPUTE #PRICE = 23.34 COMPUTE #XYZ = -103 COMPUTE #A = #B * 6074
Numeric constants are represented internally in packed form (Format P); exception: if a numeric constant is used in an arithmetic operation in which the other operand is an integer variable (Format I), the numeric constant is represented in integer form (Format I).
122
Programming Guide
User-Defined Constants
Alphanumeric Constants
The following topics are covered below:
Alphanumeric Constants
An alphanumeric constant may contain 1 to 1 1073741824 bytes (1 GB) of alphanumeric characters. An alphanumeric constant must be enclosed in either apostrophes (')
'text'
Examples:
MOVE 'ABC' TO #FIELDX MOVE '% INCREASE' TO #TITLE DISPLAY "LAST-NAME" NAME
Note: An alphanumeric constant that is used to assign a value to a user-defined variable must not be split between statement lines.
Programming Guide
123
Note: If quotation marks are not converted to apostrophes as shown above, this is due to the setting of the profile parameter TQ (Translate Quotation Marks); ask your Natural administrator for details.
In this way, alphanumeric constants can also be concatenated with hexadecimal constants.
Unicode Constants
The following topics are covered below:
Unicode Text Constants Apostrophes Within Unicode Text Constants Unicode Hexadecimal Constants
124
Programming Guide
User-Defined Constants
Example:
U'HELLO'
The compiler stores this text constant in the generated program in Unicode format (UTF-16).
Note: If quotation marks are not converted to apostrophes as shown above, this is due to the setting of the profile parameter TQ (Translate Quotation Marks); ask your Natural administrator for details.
Programming Guide
125
User-Defined Constants
where h represents a hexadecimal digit (0-9, A-F). Since a UTF-16 Unicode character consists of a double-byte, the number of hexadecimal characters supplied has to be a multiple of four. Example: This example defines the string 45.
UH'00340035'
Unicode text constants or Unicode hexadecimal constants cannot be concatenated with code page alphanumeric constants or H constants. Invalid Example:
MOVE U'ABC' - 'DEF' TO #FIELD MOVE UH'00340035' - H'414243' TO #FIELD
126
Programming Guide
User-Defined Constants
#U10 := U'A'-UH'0042'-U'C' /* Constant supplied in mixed formats, corresponds to U'ABC'. END
Date Constant
A date constant may be used in conjunction with a Format D variable. Date constants may have the following formats:
D'yyyy-mm-dd' D'dd.mm.yyyy' D'dd/mm/yyyy' D'mm/dd/yyyy'
International date format German date format European date format US date format
where dd represents the number of the day, mm the number of the month and yyyy the year. Example:
DEFINE DATA LOCAL 1 #DATE (D) END-DEFINE ... MOVE D'2004-03-08' TO #DATE ...
The default date format is controlled by the profile parameter DTFORM (Date Format) as set by the Natural administrator.
Programming Guide
127
User-Defined Constants
Time Constant
A time constant may be used in conjunction with a Format T variable. A time constant has the following format:
T'hh:ii:ss'
DEFINE DATA LOCAL 1 #TIME (T) END-DEFINE ... MOVE T'11:33:00' TO #TIME ...
With an extended time constant (prefix E), it is possible to handle the full content of a time variable, including the date information:
E'yyyy-mm-dd hh:ii:ss'
Apart from that, the use of an extended time constant in conjunction with a time variable is the same as for a normal time constant. Note: The format in which the date information has to be specified in an extended time constant depends on the setting of the profile parameter DTFORM. The extended time constant shown above assumes DTFORM=I (international date format).
128
Programming Guide
User-Defined Constants
Hexadecimal Constants
The following topics are covered below:
Hexadecimal Constants
A hexadecimal constant may be used to enter a value which cannot be entered as a standard keyboard character. A hexadecimal constant may contain 1 to 1073741824 bytes (1 GB) of alphanumeric characters. A hexadecimal constant is prefixed with an H. The constant itself must be enclosed in apostrophes and may consist of the hexadecimal characters 0 - 9, A - F. Two hexadecimal characters are required to represent one byte of data. The hexadecimal representation of a character varies, depending on whether your computer uses an ASCII or EBCDIC character set. When you transfer hexadecimal constants to another computer, you may therefore have to convert the characters. ASCII examples:
H'313233' H'414243'
(equivalent to the alphanumeric constant '123') (equivalent to the alphanumeric constant 'ABC')
EBCDIC examples:
H'F1F2F3' H'C1C2C3'
(equivalent to the alphanumeric constant '123') (equivalent to the alphanumeric constant 'ABC')
When a hexadecimal constant is transferred to another field, it will be treated as an alphanumeric value (format A). The data transfer of an alphanumeric value (format A) to a field which is defined with a format other than A,U or B is not allowed. Therefore, a hexadecimal constant used as initial value in a DEFINE DATA statement is rejected with the syntax error NAT0094 if the corresponding variable is not of format A, U or B.
Programming Guide
129
EBCDIC example:
In this way, hexadecimal constants can also be concatenated with alphanumeric constants.
Logical Constants
The logical constants TRUE and FALSE may be used to assign a logical value to a field defined with Format L. Example:
DEFINE DATA LOCAL 1 #FLAG (L) END-DEFINE ... MOVE TRUE TO #FLAG ... IF #FLAG ... statement ... MOVE FALSE TO #FLAG END-IF ...
130
Programming Guide
User-Defined Constants
DEFINE DATA LOCAL 1 #FLT1 (F4) END-DEFINE ... COMPUTE #FLT1 = -5.34E+2 ...
Attribute Constants
Attribute constants can be used with variables defined with format C (control variables). This type of constant must be enclosed within parentheses. The following attributes may be used:
Attribute Description
AD=D AD=B AD=I AD=N AD=V AD=U AD=C AD=Y AD=P CD=BL CD=GR CD=NE CD=PI CD=RE CD=TU CD=YE
default blinking intensified non-display reverse video underlined cursive/italic dynamic attribute protected blue green neutral pink red turquoise yellow
Programming Guide
131
DEFINE DATA LOCAL 1 #ATTR (C) 1 #FIELD (A10) END-DEFINE ... MOVE (AD=I CD=BL) TO #ATTR ... INPUT #FIELD (CV=#ATTR) ...
Handle Constants
The handle constant NULL-HANDLE can be used with object handles. For further information on object handles, see the section NaturalX.
Define a field in the DEFINE DATA statement, assign a constant value to it, and use the field name in the program instead of the constant value.
Thus, when the value has to be changed, you only have to change it once in the DEFINE DATA statement and not everywhere in the program where it occurs. You specify the constant value in angle brackets with the keyword CONSTANT after the field definition in the DEFINE DATA statement.
If the value is alphanumeric, it must be enclosed in apostrophes. If the value is text in Unicode format, it must be preceded by the character U and must be enclosed in apostrophes. If the value is in hexadecimal Unicode format, it must be preceded by the characters UH and must be enclosed in apostrophes.
132
Programming Guide
DEFINE DATA LOCAL 1 #FIELDA (N3) CONSTANT 1 #FIELDB (A5) CONSTANT 1 #FIELDC (U5) CONSTANT 1 #FIELDD (U5) CONSTANT END-DEFINE ...
During the execution of the program, the value of such a named constant cannot be modified.
Programming Guide
133
134
20
Default Initial Value of a User-Defined Variable/Array ............................................................................ 136 Assigning an Initial Value to a User-Defined Variable/Array ..................................................................... 136 Resetting a User-Defined Variable to its Initial Value ............................................................................. 138
135
Initial Values (and the RESET Statement) This chapter covers the following topics:
(AD=D)
Assigning a Modifiable Initial Value Assigning a Constant Initial Value Assigning a Natural System Variable as Initial Value Assigning Characters as Initial Value for Alphanumeric Variables
136
Programming Guide
DEFINE DATA LOCAL 1 #FIELDA (N3) INIT <100> 1 #FIELDB (A20) INIT <'ABC'> END-DEFINE ...
DEFINE DATA LOCAL 1 #FIELDA (N3) CONST <100> 1 #FIELDB (A20) CONST <'ABC'> END-DEFINE ...
Programming Guide
137
Filling an entire field: With the option FULL LENGTH <character(s)> the entire field is filled with the specified character(s). In this example, the entire field will be filled with asterisks.
DEFINE DATA LOCAL 1 #FIELD (A25) INIT FULL LENGTH <'*'> END-DEFINE ...
Filling the firstn positions of a field: With the option LENGTH n <character(s)> the first n positions of the field are filled with the specified character(s). In this example, the first 4 positions of the field will be filled with exclamation marks.
DEFINE DATA LOCAL 1 #FIELD (A25) INIT LENGTH 4 <'!'> END-DEFINE ...
Reset to Default Initial Value Reset to Initial Value Defined in DEFINE DATA
Notes: 1. A field declared with a CONSTANT clause in the DEFINE DATA statement may not be referenced in a RESET statement, since its content cannot be changed. 2. In reporting mode, the RESET statement may also be used to define a variable, provided that the program contains no DEFINE DATA LOCAL statement.
138
Programming Guide
DEFINE DATA LOCAL 1 #FIELDA (N3) INIT <100> 1 #FIELDB (A20) INIT <'ABC'> 1 #FIELDC (I4) INIT <5> END-DEFINE ... ... RESET #FIELDA ...
For a field declared without INIT clause in the DEFINE DATA statement, RESET INITIAL has the same effect as RESET (without INITIAL). Example:
DEFINE DATA LOCAL 1 #FIELDA (N3) INIT <100> 1 #FIELDB (A20) INIT <'ABC'> 1 #FIELDC (I4) INIT <5> END-DEFINE ... RESET INITIAL #FIELDA #FIELDB #FIELDC /* resets field values to initial values as defined in DEFINE DATA ...
Programming Guide
139
140
21
Redefining Fields
Using the REDEFINE Option of DEFINE DATA .................................................................................... 142 Example Program Illustrating the Use of a Redefinition .......................................................................... 143
141
Redefining Fields Redefinition is used to change the format of a field, or to divide a single field into segments.
DEFINE DATA LOCAL 01 EMPLOY-VIEW VIEW OF STAFFDDM 02 NAME 02 BIRTH 02 REDEFINE BIRTH 03 #BIRTH-YEAR (N4) 03 #BIRTH-MONTH (N2) 03 #BIRTH-DAY (N2) END-DEFINE ...
Example 2: In the following example, the group #VAR2, which consists of two user-defined variables of format N and P respectively, is redefined as a variable of format A:
DEFINE DATA LOCAL 01 #VAR1 (A15) 01 #VAR2 02 #VAR2A (N4.1) 02 #VAR2B (P6.2) 01 REDEFINE #VAR2 02 #VAR2RD (A10) END-DEFINE ...
142
Programming Guide
Redefining Fields With the notation FILLER nX you can define n filler bytes - that is, segments which are not to be used - in the field that is being redefined. (The definition of trailing filler bytes is optional.) Example 3: In the following example, the user-defined variable #FIELD is redefined as three new user-defined variables, each of format/length A2. The FILLER notations indicate that the 3rd and 4th and 7th to 10th bytes of the original field are not be used.
DEFINE DATA LOCAL 1 #FIELD (A12) 1 REDEFINE #FIELD 2 #RFIELD1 (A2) 2 FILLER 2X 2 #RFIELD2 (A2) 2 FILLER 4X 2 #RFIELD3 (A2) END-DEFINE ...
** Example 'DDATAX01': DEFINE DATA ************************************************************************ DEFINE DATA LOCAL 01 VIEWEMP VIEW OF EMPLOYEES 02 NAME 02 FIRST-NAME 02 SALARY (1:1) * 01 #PAY (N9) 01 REDEFINE #PAY 02 FILLER 3X 02 #USD (N3) 02 #OOO (N3) END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' MOVE SALARY (1) TO #PAY DISPLAY NAME FIRST-NAME #PAY #USD #OOO END-READ END
Programming Guide
143
Redefining Fields Output of Program DDATAX01: Note how #PAY and the fields resulting from its definition are displayed:
Page
04-11-11
14:15:54
NAME FIRST-NAME #PAY #USD #OOO -------------------- -------------------- ---------- ---- ---JONES JONES JONES VIRGINIA MARSHA ROBERT 46000 50000 31000 46 50 31 0 0 0
144
Programming Guide
22
Arrays
Defining Arrays ............................................................................................................................. 146 Initial Values for Arrays ................................................................................................................... 147 Assigning Initial Values to One-Dimensional Arrays .............................................................................. 147 Assigning Initial Values to Two-Dimensional Arrays .............................................................................. 148 A Three-Dimensional Array .............................................................................................................. 152 Arrays as Part of a Larger Data Structure ........................................................................................... 154 Database Arrays ............................................................................................................................ 155 Using Arithmetic Expressions in Index Notation ................................................................................... 155 Arithmetic Support for Arrays ........................................................................................................... 156
145
Arrays Natural supports the processing of arrays. Arrays are multi-dimensional tables, that is, two or more logically related elements identified under a single name. Arrays can consist of single data elements of multiple dimensions or hierarchical data structures which contain repetitive structures or individual elements.
Defining Arrays
In Natural, an array can be one-, two- or three-dimensional. It can be an independent variable, part of a larger data structure or part of a database view. Important: Dynamic variables are not allowed in an array definition. To define a one-dimensional array
After the format and length, specify a slash followed by a so-called index notation, that is, the number of occurrences of the array. For example, the following one-dimensional array has three occurrences, each occurrence being of format/length A10:
146
Programming Guide
Arrays A two-dimensional array can be visualized as a table. The array defined in the example above would be a table that consists of 3 rows and 4 columns:
To assign the same initial value to a range of several occurrences, you specify:
1 #ARRAY (A1/1:3) INIT (2:3) <'A'> A is assigned to the second to third occurrence.
Programming Guide
147
Arrays
To assign different initial values to some (but not all) occurrences, you specify:
1 #ARRAY (A1/1:3) INIT (1) <'A'> (3) <'C'> A is assigned to the first occurrence, and C to the third; no value is assigned to the second occur-
If fewer initial values are specified than there are occurrences, the last occurrences remain empty:
1 #ARRAY (A1/1:3) INIT <'A','B'> A is assigned to the first occurrence, and B to the second; no value is assigned to the third occur-
rence.
148
Programming Guide
Arrays
Preliminary Information
For the examples shown in this section, let us assume a two-dimensional array with three occurrences in the first dimension (rows) and four occurrences in the second dimension (columns):
1 #ARRAY (A1/1:3,1:4)
The first set of examples illustrates how the same initial value is assigned to occurrences of a twodimensional array; the second set of examples illustrates how different initial values are assigned. In the examples, please note in particular the usage of the notations * and V. Both notations refer to all occurrences of the dimension concerned: * indicates that all occurrences in that dimension are initialized with the same value, while V indicates that all occurrences in that dimension are initialized with different values.
To assign the same initial value to one occurrence in the second dimension - in all occurrences of the first dimension - you specify:
1 #ARRAY (A1/1:3,1:4) INIT (*,3) <'A'>
A A A
Programming Guide
149
Arrays
To assign the same initial value to a range of occurrences in the first dimension - in all occurrences of the second dimension - you specify:
1 #ARRAY (A1/1:3,1:4) INIT (2:3,*) <'A'>
A A A A A A A A
To assign the same initial value to a range of occurrences in each dimension, you specify:
1 #ARRAY (A1/1:3,1:4) INIT (2:3,1:2) <'A'>
A A A A
To assign the same initial value to all occurrences (in both dimensions), you specify:
1 #ARRAY (A1/1:3,1:4) INIT ALL <'A'>
A A A A A A A A A A A A
A B C
150
Programming Guide
Arrays
1 #ARRAY (A1/1:3,1:4) INIT (V,2:3) <'A','B','C'>
A A B B C C
1 #ARRAY (A1/1:3,1:4) INIT (V,*) <'A','B','C'>
A A A A B B B B C C C C
1 #ARRAY (A1/1:3,1:4) INIT (V,*) <'A',,'C'>
A A A A C C C C
1 #ARRAY (A1/1:3,1:4) INIT (V,*) <'A','B'>
A A A A B B B B
A B C
D E F
A B C D
Programming Guide
151
Arrays
1 #ARRAY (A1/1:3,1:4) INIT (*,V) <'A','B','C','D'>
A B C D A B C D A B C D
1 #ARRAY (A1/1:3,1:4) INIT (2,1) <'A'> (*,2) <'B'> (3,3) <'C'> (3,4) <'D'>
B A B B C D
1 #ARRAY (A1/1:3,1:4) INIT (2,1) <'A'> (V,2) <'B',C',D'> (3,3) <'E'> (3,4) <'F'>
B A C D E F
A Three-Dimensional Array
A three-dimensional array could be visualized as follows:
152
Programming Guide
Arrays
The array illustrated here would be defined as follows (at the same time assigning an initial value to the highlighted field in Row 1, Column 2, Plane 2):
DEFINE DATA LOCAL 1 #ARRAY2 2 #ROW (1:4) 3 #COLUMN (1:3) 4 #PLANE (1:3) 5 #FIELD2 (P3) INIT (1,2,2) <100> END-DEFINE ...
Programming Guide
153
Arrays If defined as a local data area in the data area editor, the same array would look as follows:
I T L - - 1 2 3 4 I 5 Name F Leng Index/Init/EM/Name/Comment -------------------------------- - ---- --------------------------------#ARRAY2 #ROW (1:4) #COLUMN (1:3) #PLANE (1:3) #FIELD2 P 3
DEFINE DATA LOCAL 1 #AREA 2 #FIELD1 (A10) 2 #GROUP1 (1:10) 3 #FIELD2 (P2) 3 #FIELD3 (N1/1:4) END-DEFINE ...
In this example, the data area #AREA has a total size of: 10 + (10 * (2 + (1 * 4))) bytes = 70 bytes
#FIELD1 is alphanumeric and 10 bytes long. #GROUP1 is the name of a sub-area within #AREA which
consists of 2 fields and has 10 occurrences. #FIELD2 is packed numeric, length 2. #FIELD3 is the second field of #GROUP1 with four occurrences, and is numeric, length 1. To reference a particular occurrence of #FIELD3, two indices are required: first, the occurrence of #GROUP1 must be specified, and second, the particular occurrence of #FIELD3 must also be specified. For example, in an ADD statement later in the same program, #FIELD3 would be referenced as follows:
154
Programming Guide
Arrays
ADD 2 TO #FIELD3 (3,2)
Database Arrays
Adabas supports array structures within the database in the form of multiple-value fields and periodic groups. These are described under Database Arrays. The following example shows a DEFINE DATA view containing a multiple-value field:
DEFINE DATA LOCAL 1 EMPLOYEES-VIEW VIEW OF EMPLOYEES 2 NAME 2 ADDRESS-LINE (1:10) /* <--- MULTIPLE-VALUE FIELD END-DEFINE ...
Values of the field MA are referenced, beginning with value I and ending with value I+5. Values of the field MA are referenced, beginning with value I+2 and ending with value J-3.
Only the arithmetic operators plus (+) and minus (-) may be used in index expressions.
Programming Guide
155
Arrays
1. ADD #A(*,*) TO #B(*,*) The result operand, array #B, contains the addition, element by element, of the array #A and the original value of array #B. 2. ADD 4 TO #A(*,2) The second column of the array #A is replaced by its original value plus 4. 3. ADD 2 TO #A(2,*) The second row of the array #A is replaced by its original value plus 2. 4. ADD #A(2,*) TO #B(4,*) The value of the second row of array #A is added to the fourth row of array #B. 5. ADD #A(2,*) TO #B(*,2) This is an illegal operation and will result in a syntax error. Rows may only be added to rows and columns to columns.
156
Programming Guide
Arrays 6. ADD #A(2,*) TO #C All values in the second row of the array #A are added to the scalar value #C. 7. ADD #A(2,5:7) TO #C The fifth, sixth, and seventh column values of the second row of array #A are added to the scalar value #C.
Programming Guide
157
158
23
X-Arrays
Definition ..................................................................................................................................... 160 Storage Management of X-Arrays ..................................................................................................... 161 Storage Management of X-Group Arrays ............................................................................................ 161 Referencing an X-Array ................................................................................................................... 163 Parameter Transfer with X-Arrays ..................................................................................................... 164 Parameter Transfer with X-Group Arrays ............................................................................................ 165 X-Array of Dynamic Variables ........................................................................................................... 166 Lower and Upper Bound of an Array .................................................................................................. 167
159
X-Arrays When an ordinary array field is defined, you have to specify the index bounds exactly, hence the number of occurrences for each dimension. At runtime, the complete array field is existent by default; each of its defined occurrences can be accessed without performing additional allocation operations. The size layout cannot be changed anymore; you may neither add nor remove field occurrences. However, if the number of occurrences needed is unknown at development time, but you want to flexibly increase or decrease the number of the array fields at runtime, you should use what is called an X-array (eXtensible array). An X-array can be resized at runtime and can help you manage memory more efficiently. For example, you can use a large number of array occurrences for a short time and then reduce memory when the application is no longer using the array.
Definition
An X-array is an array of which the number of occurrences is undefined at compile time. It is defined in a DEFINE DATA statement by specifying an asterisk (*) for at least one index bound of at least one array dimension. An asterisk (*) character in the index definition represents a variable index bound which can be assigned to a definite value during program execution. Only one bound - either upper or lower - may be defined as variable, but not both. An X-array can be defined whenever a (fixed) array can be defined, i.e. at any level or even as an indexed group. It cannot be used to access MU-/PE-fields of a database view. A multidimensional array may have a mixture of constant and variable bounds. Example:
DEFINE DATA LOCAL 1 #X-ARR1 (A5/1:*) 1 #X-ARR2 (A5/*) 1 #X-ARR3 (A5/*:100) 1 #X-ARR4 (A5/1:10,1:*) END-DEFINE upper bound
/* lower bound is fixed at 1, upper bound is variable /* shortcut for (A5/1:*) /* lower bound is variable, upper bound is fixed at 100 /* 1st dimension has a fixed index range with (1:10) /* 2nd dimension has fixed lower bound 1 and variable
160
Programming Guide
X-Arrays
DEFINE DATA LOCAL 1 #X-ARR(I4/10:*) END-DEFINE EXPAND ARRAY #X-ARR TO (10:10000) /* #X-ARR(10) to #X-ARR(10000) are accessible WRITE *LBOUND(#X-ARR) /* is 10 *UBOUND(#X-ARR) /* is 10000 *OCCURRENCE(#X-ARR) /* is 9991 #X-ARR(*) := 4711 /* same as #X-ARR(10:10000) := 4711 /* resize array from current lower bound=10 to upper bound =1000 RESIZE ARRAY #X-ARR TO (*:1000) /* #X-ARR(10) to #X-ARR(1000) are accessible /* #X-ARR(1001) to #X-ARR(10000) are released WRITE *LBOUND(#X-ARR) /* is 10 *UBOUND(#X-ARR) /* is 1000 *OCCURRENCE(#X-ARR) /* is 991 /* release all occurrences REDUCE ARRAY #X-ARR TO 0 WRITE *OCCURRENCE(#X-ARR) /* is 0
Programming Guide
161
DEFINE DATA LOCAL 1 #X-GROUP-ARR1(1:*) 2 #X-ARR1 (I4) 2 #X-ARR2 (I4/2:*) 2 #X-GROUP-ARR2 3 #X-ARR3 (I4) 3 #X-ARR4 (I4/3:*) 3 #X-ARR5 (I4/4:*, 5:*) END-DEFINE
/* /* /* /* /* /* /*
The following table shows whether the dimensions in the above program are independent or dependent.
Name
#X-GROUP-ARR1 #X-ARR1 #X-ARR2 (1:*) (1:*) (2:*)
#X-GROUP-ARR2 (1:*) #X-ARR3 #X-ARR4 #X-ARR5 (1:*) (1:*) (1:*) (3:*) (4:*,5:*)
The only index notation permitted for a dependent dimension is either a single asterisk (*), a range defined with asterisks (*:*) or the index bounds defined. This is to indicate that the bounds of the dependent dimension must be kept as they are and cannot be changed. The occurrences of the dependent dimensions can only be changed by manipulating the corresponding array groups.
EXPAND ARRAY #X-GROUP-ARR1 TO (1:11) EXPAND EXPAND EXPAND EXPAND EXPAND ARRAY ARRAY ARRAY ARRAY ARRAY #X-ARR2 TO (*:*, 2:12) #X-ARR2 TO (1:*, 2:12) #X-ARR2 TO (* , 2:12) #X-ARR4 TO (*:*, 3:13) #X-ARR5 TO (*:*, 4:14, 5:15)
/* #X-ARR1(1:11) are allocated /* #X-ARR3(1:11) are allocated /* #X-ARR2(1:11, 2:12) are allocated /* same as before /* same as before /* #X-ARR4(1:11, 3:13) are allocated /* #X-ARR5(1:11, 4:14, 5:15) are allocated
162
Programming Guide
X-Arrays The following use of the EXPAND statement is not allowed, since the arrays only have dependent dimensions.
EXPAND ARRAY #X-ARR1 TO ... EXPAND ARRAY #X-GROUP-ARR2 TO ... EXPAND ARRAY #X-ARR3 TO ...
Referencing an X-Array
The occurrences of an X-array must be allocated by an EXPAND or RESIZE statement before they can be accessed. As a general rule, an attempt to address a non existent X-array occurrence leads to a runtime error. In some statements however, the access to a non materialized X-array field does not cause an error situation if all occurrences of an X-array are referenced by using the complete range notation, for example: #X-ARR(*). This applies to
parameters, used in CALL statement, parameters used in CALLNAT, PERFORM or OPEN DIALOG, if defined as optional parameters, source fields used in COMPRESS statement, output fields supplied in a PRINT statement, fields referenced in a RESET statement.
If individual occurrences of a non materialized X-array are referenced in one of these statements, a corresponding error message is issued. Example:
DEFINE DATA LOCAL 1 #X-ARR (A10/1:*) /* X-array only defined, but not allocated END-DEFINE RESET #X-ARR(*) /* no error, because complete field referenced with (*) RESET #X-ARR(1:3) /* runtime error, because individual occurrences (1:3) are referenced END
The asterisk (*) notation in an array reference stands for the complete range of a dimension. If the array is an X-array, the asterisk is the index range of the current allocated lower and upper bound values which are determined by *LBOUND and *UBOUND.
Programming Guide
163
X-Arrays
In addition, X-array parameters can also change the number of occurrences by using the statement RESIZE, REDUCE or EXPAND. The question if a resize of an X-array parameter is permitted depends on three factors:
the type of parameter transfer used, that is by reference or by value, the definition of the caller or parameter X-array and the type of X-array range being passed on (complete range or subrange).
The following tables demonstrate when an EXPAND, RESIZE or REDUCE statement can be applied to an X-array parameter.
164
Programming Guide
X-Arrays
Static Variable (1:V) X-Array with a fixed lower bound, e.g. X-Array with a fixed upper bound, e.g.
NO NO
NO NO
NO NO
NO NO
NO
NO
YES
NO
NO
NO
NO
YES
Programming Guide
165
/* /* /* /* /* /*
Subprogram:
DEFINE DATA PARAMETER 1 #X-GROUP-ARR(1:*) 2 #X-PAR1 (I4) 2 #X-PAR2 (I4) END-DEFINE ... RESIZE ARRAY #X-GROUP-ARR to (1:5) ... END
The RESIZE statement in the subprogram is not possible. It would result in an inconsistent number of occurrences of the fields defined in the X-group arrays of the program.
166
Programming Guide
X-Arrays Example:
DEFINE DATA LOCAL 1 #X-ARRAY(A/1:*) DYNAMIC END-DEFINE EXPAND ARRAY #X-ARRAY TO (1:10) /* allocate #X-ARRAY(1) to #X-ARRAY(10) with zero length. /* *LENGTH(#X-ARRAY(1:10)) is zero #X-ARRAY(*) := 'abc' /* #X-ARRAY(1:10) contains 'abc', /* *LENGTH(#X-ARRAY(1:10)) is 3 EXPAND ARRAY #X-ARRAY TO (1:20) /* allocate #X-ARRAY(11) to #X-ARRAY(20) with zero length /* *LENGTH(#X-ARRAY(11:20)) is zero #X-ARRAY(11:20) := 'def' /* #X-ARRAY(11:20) contains 'def' /* *LENGTH(#X-ARRAY(11:20)) is 3
Programming Guide
167
168
24
This part describes various aspects of accessing data in a database with Natural.
Natural and Database Access Accessing Data in an Adabas Database Accessing Data in an SQL Database Accessing Data in a VSAM Database Accessing Data in a DL/I Database
See also DBMS Interface for a description of the Natural database interfaces for the various types of database Management systems.
169
170
25
Database Management Systems Supported by Natural ......................................................................... 172 Profile Parameters Influencing Database Access ................................................................................. 173 Access through Data Definition Modules ............................................................................................ 173 Natural's Data Manipulation Language ............................................................................................... 174 Natural's Special SQL Statements ..................................................................................................... 175
171
Natural and Database Access This chapter gives an overview of the facilities that Natural provides for accessing different types of database management and file management systems.
Nested-relational DBMS (Adabas) SQL-type DBMS (DB2 (SQL/DS), Oracle, Sybase, Informix, MS SQL Server) File systems (VSAM) DL/I
Adabas
Via its integrated Adabas interface, Natural can access Adabas databases either on a local machine or on remote computers. For remote access, an additional routing and communication software such as Entire Net-Work is necessary. In any case, the type of host machine running the Adabas database is transparent for the Natural user.
SQL Databases
Natural for DB2 offers one common set of statements to access DB2 and SQL/DS database management systems. For detailed information, refer to the appropriate add-on product description in the Database Management System Interfaces documentation:
172
Programming Guide
VSAM
With the Natural interface to VSAM, a Natural user can access data stored in VSAM files. For detailed information and special considerations on the use of Natural statements and system variables with VSAM, see Natural for VSAM in the Database Management System Interfaces documentation.
DL/I
With Natural for DL/I, a Natural user can access and update data stored in a DL/I database. The Natural user can be executing in batch mode or under the control of the TP monitor CICS or IMS TM. A DL/I database is represented to Natural as a set of files, each file representing one database segment type. Each file or segment type must have an associated DDM generated and stored on the Natural FDIC system file. The Natural statements used to access DL/I databases are a subset of those provided with the Natural language. No new statements are needed to access a DL/I database. For further information, see Natural for DL/I in the Database Management System Interfaces documentation..
Programming Guide
173
174
Programming Guide
Natural and Database Access Because some of the Natural DML statements provide functionality that cannot be supported for all database types, the use of this functionality is restricted to specific database systems. Please, note the corresponding database-specific considerations in the statements documentation.
Programming Guide
175
176
26
Data Definition Modules - DDMs ....................................................................................................... 178 Database Arrays ............................................................................................................................ 180 DEFINE DATA Views ...................................................................................................................... 185 Statements for Database Access ...................................................................................................... 187 Multi-Fetch Clause ......................................................................................................................... 200 Database Processing Loops ............................................................................................................ 203 Database Update - Transaction Processing ......................................................................................... 209 Selecting Records Using ACCEPT/REJECT ....................................................................................... 217 AT START/END OF DATA Statements ............................................................................................... 220 Unicode Data ................................................................................................................................ 223
177
Accessing Data in an Adabas Database This chapter describes various aspects of accessing data in an Adabas database with Natural. See also Natural with Adabas (in the Operations documentation) for an overview of the Natural profile parameters that apply when Natural is used with Adabas.
178
Programming Guide
DDMs are defined by the Natural administrator with Predict (or, if Predict is not available, with the corresponding Natural function).
Maintaining DDMs
Use the system command SYSDDM to invoke the SYSDDM utility. The SYSDDM utility is used to perform all functions needed for the creation and maintenance of Natural data definition modules. For further information on the SYSDDM utility, see the section SYSDDM Utility in the Editors documentation. For each database field, a DDM contains the database-internal field name as well as the external field name, that is, the name of the field as used in a Natural program. Moreover, the formats and lengths of the fields are defined in the DDM, as well as various specifications that are used when the fields are output with a DISPLAY or WRITE statement (column headings, edit masks, etc.). For the field attributes defined in a DDM, refer to Using the DDM Editor Screen in the section SYSDDM Utility of the Editors documentation.
Programming Guide
179
Listing/Displaying DDMs
If you do not know the name of the DDM you want, you can use the system command LIST DDM to get a list of all existing DDMs that are available in the current library. From the list, you can then select a DDM for display. To display a DDM whose name you know, you use the system command LIST DDM ddm-name. For example:
LIST DDM EMPLOYEES
A list of all fields defined in the DDM will then be displayed, along with information about each field. For the field attributes defined in a DDM, refer to SYSDDM Utility in the Editors documentation.
Database Arrays
Adabas supports array structures within the database in the form of multiple-value fields and periodic groups. This section covers the following topics:
Multiple-Value Fields Periodic Groups Referencing Multiple-Value Fields and Periodic Groups Multiple-Value Fields within Periodic Groups Referencing Multiple-Value Fields within Periodic Groups Referencing the Internal Count of a Database Array
Multiple-Value Fields
A multiple-value field is a field which can have more than one value (up to 65534, depending on the Adabas version and definition of the FDT) within a given record.
180
Programming Guide
Assuming that the above is a record in an employees file, the first field (Name) is an elementary field, which can contain only one value, namely the name of the person; whereas the second field (Languages), which contains the languages spoken by the person, is a multiple-value field, as a person can speak more than one language.
Periodic Groups
A periodic group is a group of fields (which may be elementary fields and/or multiple-value fields) that may have more than one occurrence (up to 65534, depending on the Adabas version and definition of the FDT) within a given record. The different values of a multiple-value field are usually called occurrences; that is, the number of occurrences is the number of values which the field contains, and a specific occurrence means a specific value. Similarly, in the case of periodic groups, occurrences refer to a group of values.
Programming Guide
181
Assuming that the above is a record in a vehicles file, the first field (Name) is an elementary field which contains the name of a person; Cars is a periodic group which contains the automobiles owned by that person. The periodic group consists of three fields which contain the registration number, make and model of each automobile. Each occurrence of Cars contains the values for one automobile.
182
Programming Guide
Accessing Data in an Adabas Database The various values of the multiple-value field LANGUAGES can be referenced as follows.
Example
LANGUAGES (1) LANGUAGES (X) LANGUAGES (1:3)
Explanation References the first value (SPANISH). The value of the variable X determines the value to be referenced. References the first three values (SPANISH, CATALAN and FRENCH). The values of the variables X and Y determine the values to be referenced.
The various occurrences of the periodic group CARS can be referenced in the same manner:
Example
CARS (1) CARS (X)
Explanation References the first occurrence (B-123ABC/SEAT/IBIZA). The value of the variable X determines the occurrence to be referenced.
CARS (1:2) References the first two occurrences (B-123ABC/SEAT/IBIZA and B-999XYZ/VW/GOLF). CARS (4:7) References the fourth to seventh occurrences. CARS (X:Y) The values of the variables X and Y determine the occurrences to be referenced.
Programming Guide
183
Assuming that the above is a record in a vehicles file, the first field (Name) is an elementary field which contains the name of a person; Cars is a periodic group which contains the automobiles owned by that person. The periodic group consists of three fields which contain the registration number, servicing dates and make of each automobile. Within the periodic group Cars, the field Servicing is a multiple-value field, containing the different servicing dates for each automobile.
184
Programming Guide
Accessing Data in an Adabas Database Examples: The following examples use the multiple-value field SERVICING within the periodic group CARS from the example above. The various values of the multiple-value field can be referenced as follows:
Example
SERVICING (1,1) SERVICING (1:5,1)
Explanation References the first value of SERVICING in the first occurrence of CARS (31-05-97). References the first value of SERVICING in the first five occurrences of CARS.
SERVICING (1:5,1:10) References the first ten values of SERVICING in the first five occurrences of CARS.
Explanation Returns the number of values of the multiple-value field LANGUAGES. Returns the number of occurrences of the periodic group CARS.
C*SERVICING (1) Returns the number of values of the multiple-value field SERVICING in the first occurrence of a periodic group (assuming that SERVICING is a multiple-value field
Programming Guide
185
the name of the data definition module (DDM) from which the fields are taken, and the names of the database fields themselves (that is, their long names, not their database-internal short names).
within the DEFINE DATA statement of the program, or in a local data area (LDA) or a global data area (GDA) outside the program, with the DEFINE DATA statement referencing that data area (as described in the section Defining Fields.
where view-name is the name you choose for the view, ddm-name is the name of the DDM from which the fields specified in the view are taken. At Level 2, you specify the names of the database fields from the DDM. In the illustration below, the name of the view is ABC, and it comprises the fields NAME, FIRST-NAME and PERSONNEL-ID from the DDM XYZ.
186
Programming Guide
The format and length of a database field need not be specified in the view, as these are already defined in the underlying DDM. The view may comprise an entire DDM or only a subset of it. The order of the fields in the view need not be the same as in the underlying DDM. The view name is used in database access statements to determine which database is to be accessed, as described in Statements for Database Access.
Meaning Select a range of records from a database in a specified sequence. Select from a database those records which meet a specified search criterion. a specified search criterion.
HISTOGRAM Read only the values of one database field, or determine the number of records which meet
Programming Guide
187
READ Statement
The following topics are covered:
Use of READ Statement Basic Syntax of READ Statement Example of READ Statement Limiting the Number of Records to be Read STARTING/ENDING Clauses WHERE Clause Further Example of READ Statement
Use of READ Statement The READ statement is used to read records from a database. The records can be retrieved from the database
in the order in which they are physically stored in the database (READ IN PHYSICAL SEQUENCE), or in the order of Adabas Internal Sequence Numbers (READ BY ISN), or in the order of the values of a descriptor field (READ IN LOGICAL SEQUENCE).
In this document, only READ IN LOGICAL SEQUENCE is discussed, as it is the most frequently used form of the READ statement. For information on the other two options, please refer to the description of the READ statement in the Statements documentation. Basic Syntax of READ Statement The basic syntax of the READ statement is:
READ view IN LOGICAL SEQUENCE BY descriptor
or shorter:
READ view LOGICAL BY descriptor
188
Programming Guide
is the name of a view defined in the DEFINE DATA statement (as explained in DEFINE DATA Views). order in which the records are read from the database.
descriptor is the name of a database field defined in that view. The values of this field determine the
If you specify a descriptor, you need not specify the keyword LOGICAL:
READ view BY descriptor
If you do not specify a descriptor, the records will be read in the order of values of the field defined as default descriptor (under Default Sequence) in the DDM. However, if you specify no descriptor, you must specify the keyword LOGICAL:
READ view LOGICAL
** Example 'READX01': READ ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 PERSONNEL-ID 2 JOB-TITLE END-DEFINE * READ (6) MYVIEW BY NAME DISPLAY NAME PERSONNEL-ID JOB-TITLE END-READ END
Output of Program READX01: With the READ statement in this example, records from the EMPLOYEES file are read in alphabetical order of their last names. The program will produce the following output, displaying the information of each employee in alphabetical order of the employees' last names.
Programming Guide
189
Page
1 NAME
04-11-11
14:15:54
PERSONNEL CURRENT ID POSITION -------------------- --------- ------------------------ABELLAN ACHIESON ADAM ADKINSON ADKINSON ADKINSON 60008339 30000231 50005800 20008800 20009800 2001100 MAQUINISTA DATA BASE ADMINISTRATOR CHEF DE SERVICE PROGRAMMER DBA
If you wanted to read the records to create a report with the employees listed in sequential order by date of birth, the appropriate READ statement would be:
READ MYVIEW BY BIRTH
You can only specify a field which is defined as a descriptor in the underlying DDM (it can also be a subdescriptor, superdescriptor, hyperdescriptor or phonetic descriptor or a non-descriptor). Limiting the Number of Records to be Read As shown in the previous example program, you can limit the number of records to be read by specifying a number in parentheses after the keyword READ:
READ (6) MYVIEW BY NAME
In that example, the READ statement would read no more than 6 records. Without the limit notation, the above READ statement would read all records from the EMPLOYEES file in the order of last names from A to Z. STARTING/ENDING Clauses The READ statement also allows you to qualify the selection of records based on the value of a descriptor field. With an EQUAL TO/STARTING FROM option in the BY or WITH clause, you can specify the value at which reading should begin. By adding a THRU/ENDING AT option, you can also specify the value in the logical sequence at which reading should end.
190
Programming Guide
Accessing Data in an Adabas Database For example, if you wanted a list of those employees in the order of job titles starting with TRAINEE and continuing on to Z, you would use one of the following statements:
WITH JOB-TITLE = 'TRAINEE' WITH JOB-TITLE STARTING from 'TRAINEE' BY JOB-TITLE = 'TRAINEE' BY JOB-TITLE STARTING from 'TRAINEE'
Note that the value to the right of the equal sign (=) or STARTING FROM option must be enclosed in apostrophes. If the value is numeric, this text notation is not required. If a BY option is used, a WITH option cannot be used and vice versa. The sequence of records to be read can be even more closely specified by adding an end limit with a THRU or ENDING AT clause. To read just the records with the job title TRAINEE, you would specify:
READ MYVIEW BY JOB-TITLE STARTING from 'TRAINEE' THRU 'TRAINEE' READ MYVIEW WITH JOB-TITLE EQUAL TO 'TRAINEE' ENDING AT 'TRAINEE'
To read just the records with job titles that begin with A or B, you would specify:
READ MYVIEW BY JOB-TITLE = 'A' THRU 'C' READ MYVIEW WITH JOB-TITLE STARTING from 'A' ENDING AT 'C'
The values are read up to and including the value specified after THRU/ENDING AT. In the two examples above, all records with job titles that begin with A or B are read; if there were a job title C, this would also be read, but not the next higher value CA. WHERE Clause The WHERE clause may be used to further qualify which records are to be read.
Programming Guide
191
Accessing Data in an Adabas Database For instance, if you wanted only those employees with job titles starting from TRAINEE who are paid in US currency, you would specify:
The WHERE clause can also be used with the BY clause as follows:
The WHERE clause differs from the BY/WITH clause in two respects:
The field specified in the WHERE clause need not be a descriptor. The expression following the WHERE option is a logical condition.
The following program illustrates the use of the STARTING FROM, ENDING AT and WHERE clauses:
** Example 'READX02': READ (with STARTING, ENDING and WHERE clause) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 INCOME (1:2) 3 CURR-CODE 3 SALARY 3 BONUS (1:1) END-DEFINE * READ (3) MYVIEW WITH JOB-TITLE STARTING FROM 'TRAINEE' ENDING AT 'TRAINEE' WHERE CURR-CODE (*) = 'USD' DISPLAY NOTITLE NAME / JOB-TITLE 5X INCOME (1:2)
192
Programming Guide
INCOME CURRENCY ANNUAL BONUS CODE SALARY -------- ---------- ---------USD USD USD USD USD USD 23000 21800 25000 23000 24000 22000 0 0 0 0 0 0
FIND Statement
The following topics are covered:
Use of FIND Statement Basic Syntax of FIND Statement Limiting the Number of Records to be Processed WHERE Clause Example of FIND Statement with WHERE Clause IF NO RECORDS FOUND Condition
Programming Guide
193
Use of FIND Statement The FIND statement is used to select from a database those records which meet a specified search criterion. Basic Syntax of FIND Statement The basic syntax of the FIND statement is:
FIND RECORDS IN view WITH field = value
or shorter:
FIND view WITH field = value
- where
view field
is the name of a view defined in the DEFINE DATA statement (as explained in DEFINE DATA Views). is the name of a database field defined in that view.
You can only specify a field which is defined as a descriptor in the underlying DDM (it can also be a subdescriptor, superdescriptor, hyperdescriptor or phonetic descriptor). For the complete syntax, refer to the FIND statement documentation. Limiting the Number of Records to be Processed In the same way as with the READ statement described above, you can limit the number of records to be processed by specifying a number in parentheses after the keyword FIND:
FIND (6) RECORDS IN MYVIEW WITH NAME = 'CLEGG'
In the above example, only the first 6 records that meet the search criterion would be processed. Without the limit notation, all records that meet the search criterion would be processed. Note: If the FIND statement contains a WHERE clause (see below), records which are rejected as a result of the WHERE clause are not counted against the limit.
194
Programming Guide
Accessing Data in an Adabas Database WHERE Clause With the WHERE clause of the FIND statement, you can specify an additional selection criterion which is evaluated after a record (selected with the WITH clause) has been read and before any processing is performed on the record. Example of FIND Statement with WHERE Clause
** Example 'FINDX01': FIND (with WHERE) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 JOB-TITLE 2 CITY END-DEFINE * FIND MYVIEW WITH CITY = 'PARIS' WHERE JOB-TITLE = 'INGENIEUR COMMERCIAL' DISPLAY NOTITLE CITY JOB-TITLE PERSONNEL-ID NAME END-FIND END
Note: In this example only those records which meet the criteria of the WITH clause and the
WHERE clause are processed in the DISPLAY statement.
CURRENT PERSONNEL NAME POSITION ID -------------------- ------------------------- --------- -------------------PARIS PARIS PARIS PARIS PARIS PARIS PARIS INGENIEUR INGENIEUR INGENIEUR INGENIEUR INGENIEUR INGENIEUR INGENIEUR COMMERCIAL COMMERCIAL COMMERCIAL COMMERCIAL COMMERCIAL COMMERCIAL COMMERCIAL 50007300 50006500 50004700 50004400 50002800 50001000 50000400 CAHN MAZUY FAURIE VALLY BRETON GIGLEUX KORAB-BRZOZOWSKI
CITY
Programming Guide
195
Accessing Data in an Adabas Database IF NO RECORDS FOUND Condition If no records are found that meet the search criteria specified in the WITH and WHERE clauses, the statements within the FIND processing loop are not executed (for the previous example, this would mean that the DISPLAY statement would not be executed and consequently no employee data would be displayed). However, the FIND statement also provides an IF NO RECORDS FOUND clause, which allows you to specify processing you wish to be performed in the case that no records meet the search criteria. Example:
** Example 'FINDX02': FIND (with IF NO RECORDS FOUND) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME END-DEFINE * FIND MYVIEW WITH NAME = 'BLACKSMITH' IF NO RECORDS FOUND WRITE 'NO PERSON FOUND.' END-NOREC DISPLAY NAME FIRST-NAME END-FIND END
The above program selects all records in which the field NAME contains the value BLACKSMITH. For each selected record, the name and first name are displayed. If no record with NAME = 'BLACKSMITH' is found on the file, the WRITE statement within the IF NO RECORDS FOUND clause is executed. Output of Program FINDX02:
Page
04-11-11
14:15:54
196
Programming Guide
Accessing Data in an Adabas Database Further Examples of FIND Statement See the following example programs:
FINDX07 - FIND (with several clauses) FINDX08 - FIND (with LIMIT) FINDX09 - FIND (using *NUMBER, *COUNTER, *ISN) FINDX10 - FIND (combined with READ) FINDX11 - FIND NUMBER (with *NUMBER)
HISTOGRAM Statement
The following topics are covered:
Use of HISTOGRAM Statement Syntax of HISTOGRAM Statement Limiting the Number of Values to be Read STARTING/ENDING Clauses WHERE Clause Example of HISTOGRAM Statement
Use of HISTOGRAM Statement The HISTOGRAM statement is used to either read only the values of one database field, or determine the number of records which meet a specified search criterion. The HISTOGRAM statement does not provide access to any database fields other than the one specified in the HISTOGRAM statement. Syntax of HISTOGRAM Statement The basic syntax of the HISTOGRAM statement is:
HISTOGRAM VALUE IN view FOR field
Programming Guide
197
- where
view field
is the name of a view defined in the DEFINE DATA statement (as explained in DEFINE DATA Views). is the name of a database field defined in that view.
For the complete syntax, refer to the HISTOGRAM statement documentation. Limiting the Number of Values to be Read In the same way as with the READ statement, you can limit the number of values to be read by specifying a number in parentheses after the keyword HISTOGRAM:
HISTOGRAM (6) MYVIEW FOR NAME
In the above example, only the first 6 values of the field NAME would be read. Without the limit notation, all values would be read. STARTING/ENDING Clauses Like the READ statement, the HISTOGRAM statement also provides a STARTING FROM clause and an ENDING AT (or THRU) clause to narrow down the range of values to be read by specifying a starting value and ending value. Examples:
HISTOGRAM MYVIEW FOR NAME STARTING from 'BOUCHARD' HISTOGRAM MYVIEW FOR NAME STARTING from 'BOUCHARD' ENDING AT 'LANIER' HISTOGRAM MYVIEW FOR NAME from 'BLOOM' THRU 'ROESER'
198
Programming Guide
Accessing Data in an Adabas Database WHERE Clause The HISTOGRAM statement also provides a WHERE clause which may be used to specify an additional selection criterion that is evaluated after a value has been read and before any processing is performed on the value. The field specified in the WHERE clause must be the same as in the main clause of the HISTOGRAM statement. Example of HISTOGRAM Statement
** Example 'HISTOX01': HISTOGRAM ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 CITY END-DEFINE * LIMIT 8 HISTOGRAM MYVIEW CITY STARTING FROM 'M' DISPLAY NOTITLE CITY 'NUMBER OF/PERSONS' *NUMBER *COUNTER END-HISTOGRAM END
In this program, the system variables *NUMBER and *COUNTER are also evaluated by the HISTOGRAM statement, and output with the DISPLAY statement. *NUMBER contains the number of database records that contain the last value read; *COUNTER contains the total number of values which have been read. Output of Program HISTOX01:
NUMBER OF CNT PERSONS -------------------- ----------- ----------MADISON MADRID MAILLY LE CAMP MAMERS MANSFIELD MARSEILLE MATLOCK MELBOURNE 3 41 1 1 4 2 1 2 1 2 3 4 5 6 7 8
CITY
Programming Guide
199
Multi-Fetch Clause
This section covers the multi-fetch record retrieval functionality for Adabas databases. The multi-fetch functionality described in this section is only supported for Adabas. For information on the multi-fetch record retrieval functionality for DB2 databases, see also Multiple Row Processing in the Natural for DB2 part of the Database Management System Interfaces documentation. The following topics are covered:
Purpose of Multi-Fetch Feature Considerations for Multi-Fetch Usage Size of the Multi-Fetch Buffer TEST DBLOG Support for Multi-Fetch
Where the multi-fetch-factor is either a constant or a variable with a format integer (I4). At statement execution time, the runtime checks if a multi-fetch-factor greater than 1 is supplied for the database statement.
200
Programming Guide
A multi-fetch access is only supported for a browse loop; in other words, when the records are read with no hold. The program does not receive fresh records from the database for every loop, but operates with images retrieved at the most recent multi-fetch access. If a loop repositioning is triggered for a READ / HISTOGRAM statement, the content of the multifetch buffer at that point is released. If a dynamic direction change (IN DYNAMIC...SEQUENCE) is coded for a READ / HISTOGRAM statement, the multi-fetch feature is not possible and leads to a corresponding syntax error at compilation. The first record of a FIND loop is retrieved with the initial S1 command. Since Adabas multifetch is just defined for all kinds of Lx commands, it first can be used from the second record. The size occupied by a database loop in the multi-fetch buffer is determined according to the rule:
((record-buffer-length + isn-buffer-entry-length) * multi-fetch-factor ) + 4 + header-length = ((size-of-view-fields + 20) * multi-fetch-factor) + 4 + 128
In order to keep the required space small, the multi-fetch factor is automatically reduced at runtime, if
the loop-limit (e.g. READ (2) ..) is smaller, but only if no WHERE clause is involved; the ISN quantity (for FIND statement only) is smaller; the resulting size of the record buffer or ISN buffer exceeds 32KB.
Programming Guide
201
the multi-fetch buffer is not available or does not have enough free space (for more details, refer to Size of the Multi-Fetch Buffer below.
At session start, you can also use the profile parameter DS:
DS=(MULFETCH,nn)
where nn represents the complete size allowed to be allocated for multi-fetch purposes (in KB). The value may be set in the range (0 - 1024), with a default value of 64. Setting a high value does not necessarily mean having a buffer allocated of that size, since the multi-fetch handler makes dynamic allocations and resizes, depending on what is really needed to execute a multi-fetch database statement. If no multi-fetch database statement is executed in a Natural session, the multifetch buffer will never be created, regardless of which value was set. If value 0 is specified, the multi-fetch processing is completely disabled, no matter if a database access statement contains a MULTI-FETCH OF .. clause or not. This allows to completely switch off all multi-fetch activities when there is not enough storage available in the current environment or for debugging purposes. Note: Due to existing Adabas limitations, you may not have a record buffer or ISN buffer larger than 32 KB. Therefore you need only a maximum of 64 KB space in the multi-fetch buffer for a single FIND, READ or HISTOGRAM loop. The required value setting for the multifetch buffer depends on the number of nested database loops you want to serve with multifetch.
202
Programming Guide
Creation of Database Processing Loops Hierarchies of Processing Loops Example of Nested FIND Loops Accessing the Same File Further Examples of Nested READ and FIND Statements
If the FIND statement contained a WHERE clause in addition to the WITH clause, only those records that were selected as a result of the WITH clause and met the WHERE criteria would be processed.
Programming Guide
203
Accessing Data in an Adabas Database The following diagram illustrates the flow logic of a database processing loop:
204
Programming Guide
The above program selects from the EMPLOYEES file all people with the name ADKINSON. Each record (person) selected is then processed as follows: 1. The second FIND statement is executed to select the automobiles from the VEHICLES file, using as selection criterion the PERSONNEL-IDs from the records selected from the EMPLOYEES file with the first FIND statement. 2. The NAME of each person selected is displayed; this information is obtained from the EMPLOYEES file. The MAKE and MODEL of each automobile owned by that person is also displayed; this information is obtained from the VEHICLES file. The second FIND statement creates an inner processing loop within the outer processing loop of the first FIND statement, as shown in the following diagram.
Programming Guide
205
Accessing Data in an Adabas Database The diagram illustrates the flow logic of the hierarchy of processing loops in the previous example program:
206
Programming Guide
Programming Guide
207
** Example 'FINDX05': FIND (two FIND statements on same file nested) ************************************************************************ DEFINE DATA LOCAL 1 PERSONVIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 1 #NAME (A40) END-DEFINE * WRITE TITLE LEFT JUSTIFIED 'PEOPLE IN SAME CITY AS:' #NAME / 'CITY:' CITY SKIP 1 * FIND PERSONVIEW WITH NAME = 'JONES' WHERE FIRST-NAME = 'LAUREL' COMPRESS NAME FIRST-NAME INTO #NAME /* FIND PERSONVIEW WITH CITY = CITY DISPLAY NAME FIRST-NAME CITY END-FIND END-FIND END
The above program first selects all people with name JONES and first name LAUREL from the EMPLOYEES file. Then all who live in the same city are selected from the EMPLOYEES file and a list of these people is created. All field values displayed by the DISPLAY statement are taken from the second FIND statement. Output of Program FINDX05:
PEOPLE IN SAME CITY AS: JONES LAUREL CITY: BALTIMORE NAME FIRST-NAME CITY -------------------- -------------------- -------------------JENSON LAWLER FORREST ALEXANDER NEEDHAM ZINN JONES MARTHA EDDIE CLARA GIL SUNNY CARLOS LAUREL BALTIMORE BALTIMORE BALTIMORE BALTIMORE BALTIMORE BALTIMORE BALTIMORE
208
Programming Guide
READX04 - READ statement (in combination with FIND and the system variables *NUMBER and *COUNTER) LIMITX01 - LIMIT statement (for READ, FIND loop processing)
Logical Transaction Record Hold Logic Backing Out a Transaction Restarting a Transaction Example of Using Transaction Data to Restart a Transaction
Logical Transaction
Natural performs database updating operations based on transactions, which means that all database update requests are processed in logical transaction units. A logical transaction is the smallest unit of work (as defined by you) which must be performed in its entirety to ensure that the information contained in the database is logically consistent. A logical transaction may consist of one or more update statements (DELETE, STORE, UPDATE) involving one or more database files. A logical transaction may also span multiple Natural programs. A logical transaction begins when a record is put on hold; Natural does this automatically when the record is read for updating, for example, if a FIND loop contains an UPDATE or DELETE statement. The end of a logical transaction is determined by an END TRANSACTION statement in the program. This statement ensures that all updates within the transaction have been successfully applied, and releases all records that were put on hold during the transaction.
Programming Guide
209
DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME END-DEFINE FIND MYVIEW WITH NAME = 'SMITH' DELETE END TRANSACTION END-FIND END
Each record selected would be put on hold, deleted, and then - when the END TRANSACTION statement is executed - released from hold. Note: The Natural profile parameter ETEOP, as set by the Natural administrator, determines whether or not Natural will generate an END TRANSACTION statement at the end of each Natural program. Ask your Natural administrator for details. Example of STORE Statement: The following example program adds new records to the EMPLOYEES file.
** Example 'STOREX01': STORE (Add new records to EMPLOYEES file) * ** CAUTION: Executing this example will modify the database records! ************************************************************************ DEFINE DATA LOCAL 1 EMPLOYEE-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID(A8) 2 NAME (A20) 2 FIRST-NAME (A20) 2 MIDDLE-I (A1) 2 SALARY (P9/2) 2 MAR-STAT (A1) 2 BIRTH (D) 2 CITY (A20) 2 COUNTRY (A3) * 1 #PERSONNEL-ID (A8) 1 #NAME (A20) 1 #FIRST-NAME (A20) 1 #INITIAL (A1) 1 #MAR-STAT (A1) 1 #SALARY (N9) 1 #BIRTH (A8) 1 #CITY (A20) 1 #COUNTRY (A3)
210
Programming Guide
Programming Guide
211
212
Programming Guide
ENTER A PERSONNEL ID AND NAME (OR 'END' TO END) PERSONNEL ID : NAME FIRST NAME : :
The maximum time that a record can be in hold status is determined by the Adabas transaction time limit (Adabas parameter TT). If this time limit is exceeded, you will receive an error message and all database modifications done since the last END TRANSACTION will be made undone. The number of records on hold and the transaction time limit are affected by the size of a transaction, that is, by the placement of the END TRANSACTION statement in the program. Restart facilities should be considered when deciding where to issue an END TRANSACTION. For example, if a majority of records being processed are not to be updated, the GET statement is an efficient way of controlling the holding of records. This avoids issuing multiple END TRANSACTION statements and reduces the number of ISNs on hold. When you process large files, you should bear in mind that the GET statement requires an additional Adabas call. An example of a GET statement is shown below. The placing of records in hold status is also controlled by the profile parameter RI (Release ISNs), as set by the Natural administrator.
Programming Guide
213
** Example 'GETX01': GET (put single record in hold with UPDATE stmt) ** ** CAUTION: Executing this example will modify the database records! *********************************************************************** DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 SALARY (1) END-DEFINE * RD. READ EMPLOY-VIEW BY NAME DISPLAY EMPLOY-VIEW IF SALARY (1) > 1500000 /* GE. GET EMPLOY-VIEW *ISN (RD.) /* WRITE '=' (50) 'RECORD IN HOLD:' *ISN(RD.) COMPUTE SALARY (1) = SALARY (1) * 1.15 UPDATE (GE.) END TRANSACTION END-IF END-READ END
Restarting a Transaction
With the END TRANSACTION statement, you can also store transaction-related information. If processing of the transaction terminates abnormally, you can read this information with a GET TRANSACTION DATA statement to ascertain where to resume processing when you restart the transaction.
214
Programming Guide
** Example 'GETTRX01': GET TRANSACTION * ** CAUTION: Executing this example will modify the database records! ************************************************************************ DEFINE DATA LOCAL 01 PERSON VIEW OF EMPLOYEES 02 PERSONNEL-ID (A8) 02 NAME (A20) 02 FIRST-NAME (A20) 02 MIDDLE-I (A1) 02 CITY (A20) 01 AUTO VIEW OF VEHICLES 02 PERSONNEL-ID (A8) 02 MAKE (A20) 02 MODEL (A20) * 01 ET-DATA 02 #APPL-ID (A8) INIT <' '> 02 #USER-ID (A8) 02 #PROGRAM (A8) 02 #DATE (A10) 02 #TIME (A8) 02 #PERSONNEL-NUMBER (A8) END-DEFINE * GET TRANSACTION DATA #APPL-ID #USER-ID #PROGRAM #DATE #TIME #PERSONNEL-NUMBER * IF #APPL-ID NOT = 'NORMAL' /* if last execution ended abnormally AND #APPL-ID NOT = ' ' INPUT (AD=OIL) // 20T '*** LAST SUCCESSFUL TRANSACTION ***' (I) / 20T '***********************************' /// 25T 'APPLICATION:' #APPL-ID / 32T 'USER:' #USER-ID / 29T 'PROGRAM:' #PROGRAM / 24T 'COMPLETED ON:' #DATE 'AT' #TIME / 20T 'PERSONNEL NUMBER:' #PERSONNEL-NUMBER END-IF * REPEAT /* INPUT (AD=MIL) // 20T 'ENTER PERSONNEL NUMBER:' #PERSONNEL-NUMBER
Programming Guide
215
216
Programming Guide
Statements Usable with ACCEPT and REJECT Example of ACCEPT Statement Logical Condition Criteria in ACCEPT/REJECT Statements Example of ACCEPT Statement with AND Operator Example of REJECT Statement with OR Operator Further Examples of ACCEPT and REJECT Statements
** Example 'ACCEPX01': ACCEPT IF ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 CURR-CODE (1:1) 2 SALARY (1:1) END-DEFINE * READ (20) MYVIEW BY NAME WHERE CURR-CODE (1) = 'USD' ACCEPT IF SALARY (1) >= 40000 DISPLAY NAME JOB-TITLE SALARY (1) END-READ END
Programming Guide
217
Page
1 NAME
04-11-11
11:11:11
CURRENT ANNUAL POSITION SALARY -------------------- ------------------------- ---------ADKINSON ADKINSON ADKINSON AFANASSIEV ALEXANDER ANDERSON ATHERTON ATHERTON DBA MANAGER MANAGER DBA DIRECTOR MANAGER ANALYST MANAGER 46700 47000 47000 42800 48000 50000 43000 40000
Logical condition criteria in ACCEPT / REJECT statements may also be connected with the Boolean operators AND, OR, and NOT. Moreover, parentheses may be used to indicate logical grouping; see the following examples.
218
Programming Guide
CURRENT ANNUAL POSITION SALARY -------------------- ------------------------- ---------AFANASSIEV ATHERTON ATHERTON DBA ANALYST MANAGER 42800 43000 40000
Programming Guide
219
CURRENT ANNUAL POSITION SALARY -------------------- ------------------------- ---------AFANASSIEV ATHERTON ATHERTON DBA ANALYST MANAGER 42800 43000 40000
ACCEPX04 - ACCEPT IF ... LESS THAN ... ACCEPX05 - ACCEPT IF ... AND ... ACCEPX06 - REJECT IF ... OR ...
AT START OF DATA Statement AT END OF DATA Statement Example of AT START OF DATA and AT END OF DATA Statements
220
Programming Guide
Programming Guide
221
CURRENCY ANNUAL BONUS CODE SALARY --------------- --------------- -------- ---------- ---------RUN TIME: 12:43:19.1 DUYVERMAN PRATT MARKUSH PROGRAMMER SALES PERSON TRAINEE USD USD USD 34000 38000 22000 0 9000 0
AVERAGE SALARY:
31333
ATENDX01 - AT END OF DATA ATSTAX02 - AT START OF DATA WRITEX09 - WRITE (in combination with AT END OF DATA )
222
Programming Guide
Unicode Data
Natural enables users to access wide-character fields (format W) in an Adabas database. The following topics are covered:
Access Configuration
Natural receives data from Adabas and sends data to Adabas using UTF-16 as common encoding. This encoding is specified with the OPRB parameter and sent to Adabas with the open request. It is used for wide-character fields and applies to the entire Adabas user session.
Restrictions
Collating descriptors are not supported. For further information on Adabas and Unicode support refer to the specific Adabas product documentation.
Programming Guide
223
224
27
On principle, the features and examples contained in the document Accessing Data in an Adabas Database also apply to the SQL databases supported by Natural. Differences, if any, are described in the documents for the individual database access statements (see the Statements documentation) in paragraphs named Database-Specific Considerations or in the documents for the individual Natural parameters (see the Parameter Reference). In addition, Natural for DB2 offers a specific set of statements to access DB2 and SQL/DS database management systems. For detailed information, refer to the appropriate add-on product description in the Database Management System Interfaces documentation:
Natural for DB2 Natural for SQL/DS Natural Gateway for SQL
225
226
28
On principle, the features and examples contained in the document Accessing Data in an Adabas Database also apply to VSAM databases. Differences, if any, are described in the documents for the individual database access statements (see the Statements documentation) in paragraphs named Database-Specific Considerations or in the documents for the individual Natural parameters (see the Parameter Reference). For detailed information, refer to the following add-on product description in the Database Management System Interfaces documentation:
227
228
29
On principle, the features and examples contained in the document Accessing Data in an Adabas Database also apply to DL/I databases. Differences, if any, are described in the documents for the individual database access statements (see the Statements documentation) in paragraphs named Database-Specific Considerations or in the documents for the individual Natural parameters (see the Parameter Reference). For detailed information, refer to the following add-on product description in the Database Management System Interfaces documentation:
229
230
30
This part describes how to proceed if a Natural program is to produce multiple reports. Furthermore, it discusses various aspects of how you can control the format of an output report created with Natural, that is, the way in which the data are displayed.
Report Specification - (rep) Notation Layout of an Output Page Statements DISPLAY and WRITE Index Notation for Multiple-Value Fields and Periodic Groups Page Titles, Page Breaks, Blank Lines Column Headers Parameters to Influence the Output of Fields Edit Masks - EM Parameter Vertical Displays
231
232
31
Use of Report Specifications ............................................................................................................ 234 Statements Concerned ................................................................................................................... 234 Examples of Report Specification ...................................................................................................... 234
233
Statements Concerned
The notation (rep) can be used with the following output statements:
AT END OF PAGE | AT TOP OF PAGE | COMPOSE | DISPLAY | EJECT | FORMAT | NEWPAGE | PRINT | SKIP | SUSPEND IDENTICAL SUPPRESS | WRITE | WRITE TITLE | WRITE TRAILER
234
Programming Guide
32
Statements Influencing a Report Layout ............................................................................................. 236 General Layout Example ................................................................................................................. 237
235
AT END OF PAGE
AT START OF DATA
AT END OF DATA
DISPLAY / WRITE
The relevance of the statements AT START OF DATA and AT END OF DATA for the output of data is described under Database Access, AT START/END OF DATA Statements. The other statements listed above are discussed in other sections of the part Controlling Data Output.
236
Programming Guide
** Example 'OUTPUX01': Several sections of output ************************************************************************ DEFINE DATA LOCAL 1 EMP-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 BIRTH END-DEFINE * WRITE TITLE '********** Page Title **********' WRITE TRAILER '********** Page Trailer **********' * AT TOP OF PAGE WRITE '===== Top of Page =====' END-TOPPAGE AT END OF PAGE WRITE '===== End of Page =====' END-ENDPAGE * READ (10) EMP-VIEW BY NAME /* DISPLAY NAME FIRST-NAME BIRTH (EM=YYYY-MM-DD) /* AT START OF DATA WRITE '>>>>> Start of Data >>>>>' END-START AT END OF DATA WRITE '<<<<< End of Data <<<<<' END-ENDDATA END-READ END
********** Page Title ********** ===== Top of Page ===== NAME FIRST-NAME DATE OF BIRTH -------------------- -------------------- --------->>>>> Start of Data >>>>>
Programming Guide
237
238
Programming Guide
33
DISPLAY Statement ....................................................................................................................... 240 WRITE Statement .......................................................................................................................... 241 Example of DISPLAY Statement ....................................................................................................... 242 Example of WRITE Statement .......................................................................................................... 243 Column Spacing - SF Parameter and nX Notation ................................................................................ 243 Tab Setting - nT Notation ................................................................................................................. 245 Line Advance - Slash Notation ......................................................................................................... 245 Further Examples of DISPLAY and WRITE Statements ......................................................................... 248
239
DISPLAY Statement
The DISPLAY statement produces output in column format; that is, the values for one field are output in a column underneath one another. If multiple fields are output, that is, if multiple columns are produced, these columns are output next to one another horizontally. The order in which fields are displayed is determined by the sequence in which you specify the field names in the DISPLAY statement. The DISPLAY statement in the following program displays for each person first the personnel number, then the name and then the job title:
** Example 'DISPLX01': DISPLAY ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * READ (3) VIEWEMP BY BIRTH DISPLAY PERSONNEL-ID NAME JOB-TITLE END-READ END
Page
04-11-11
14:15:54
PERSONNEL NAME CURRENT ID POSITION --------- -------------------- ------------------------30020013 30016112 20017600 GARRET TAILOR PIETSCH TYPIST WAREHOUSEMAN SECRETARY
240
Programming Guide
Statements DISPLAY and WRITE To change the order of the columns that appear in the output report, simply reorder the field names in the DISPLAY statement. For example, if you prefer to list employee names first, then job titles followed by personnel numbers, the appropriate DISPLAY statement would be:
** Example 'DISPLX02': DISPLAY ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * READ (3) VIEWEMP BY BIRTH DISPLAY NAME JOB-TITLE PERSONNEL-ID END-READ END
Page
1 NAME
04-11-11
14:15:54
CURRENT PERSONNEL POSITION ID -------------------- ------------------------- --------GARRET TAILOR PIETSCH TYPIST WAREHOUSEMAN SECRETARY 30020013 30016112 20017600
A header is output above each column. Various ways to influence this header are described in the document Column Headers.
WRITE Statement
The WRITE statement is used to produce output in free format (that is, not in columns). In contrast to the DISPLAY statement, the following applies to the WRITE statement:
If necessary, it automatically creates a line advance; that is, a field or text element that does not fit onto the current output line, is automatically output in the next line. It does not produce any headers. The values of a multiple-value field are output next to one another horizontally, and not underneath one another.
Programming Guide
241
Statements DISPLAY and WRITE The two example programs shown below illustrate the basic differences between the DISPLAY statement and the WRITE statement. You can also use the two statements in combination with one another, as described later in the document Vertical Displays, Combining DISPLAY and WRITE .
Page
1 NAME FIRST-NAME
04-11-11
14:15:54
ANNUAL SALARY -------------------- -------------------- ---------JONES VIRGINIA 46000 42300 39300 50000 46000 42700
JONES
MARSHA
242
Programming Guide
Programming Guide
243
Statements DISPLAY and WRITE With the nX notation in the DISPLAY statement, you can specify the number of spaces (n) to be inserted between two columns. An nX notation overrides the specification made with the SF parameter.
** Example 'DISPLX04': DISPLAY (with nX) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * FORMAT SF=3 READ (3) VIEWEMP BY BIRTH DISPLAY PERSONNEL-ID NAME 5X JOB-TITLE END-READ END
Output of Program DISPLX04: The above example program produces the following output, where the first two columns are separated by 3 spaces due to the SF parameter in the FORMAT statement, while the second and third columns are separated by 5 spaces due to the notation 5X in the DISPLAY statement:
14:15:54
The nX notation is also available with the WRITE statement to insert spaces between individual output elements:
WRITE PERSONNEL-ID 5X NAME 3X JOB-TITLE
With the above statement, 5 spaces will be inserted between the fields PERSONNEL-ID and NAME, and 3 spaces between NAME and JOB-TITLE.
244
Programming Guide
** Example 'DISPLX05': DISPLAY (with nT) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY 5T NAME 30T FIRST-NAME END-READ END
Output of Program DISPLX05: The above program produces the following output, where the field NAME is output starting in the 5th position (counted from the left margin of the page), and the field FIRST-NAME starting in the 30th position:
Page
04-11-11
14:15:54
In a DISPLAY statement, a slash causes a line advance between fields and within text. In a WRITE statement, a slash causes a line advance only when placed between fields; within text, it is treated like an ordinary text character.
When placed between fields, the slash must have a blank on either side.
Programming Guide
245
Statements DISPLAY and WRITE For multiple line advances, you specify multiple slashes. Example 1 - Line Advance in DISPLAY Statement:
** Example 'DISPLX06': DISPLAY (with slash '/') ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 DEPARTMENT END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME / FIRST-NAME 'DEPART-/MENT' DEPARTMENT END-READ END
Output of Program DISPLX06: The above DISPLAY statement produces a line advance after each value of the field NAME and within the text DEPART-MENT:
Page
04-11-11
14:15:54
NAME DEPARTFIRST-NAME MENT -------------------- ------JONES VIRGINIA JONES MARSHA JONES ROBERT SALE MGMT TECH
** Example 'WRITEX02': WRITE (with line advance) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 DEPARTMENT END-DEFINE *
246
Programming Guide
Output of Program WRITEX02: The above WRITE statement produces a line advance after each value of the field NAME, and a double line advance after each value of the field DEPARTMENT, but none within the text DEPART-/MENT:
04-11-11
14:15:55
DEPART-/MENT SALE
JONES MARSHA
DEPART-/MENT MGMT
JONES ROBERT
DEPART-/MENT TECH
** Example 'DISPLX21': DISPLAY (usage of slash '/' in DISPLAY and WRITE) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 FIRST-NAME 2 ADDRESS-LINE (1) END-DEFINE * WRITE TITLE LEFT JUSTIFIED UNDERLINED *TIME 5X 'PEOPLE LIVING IN SALT LAKE CITY' 21X 'PAGE:' *PAGE-NUMBER / 15X 'AS OF' *DAT4E // * WRITE TRAILER UNDERLINED 'REGISTER OF' / 'SALT LAKE CITY' * READ (2) EMPLOY-VIEW WITH CITY = 'SALT LAKE CITY' DISPLAY NAME / FIRST-NAME 'HOME/CITY' CITY 'STREET/OR BOX NO.' ADDRESS-LINE (1) SKIP 1
Programming Guide
247
14:15:54.6
PAGE:
------------------------------------------------------------------------------NAME HOME STREET FIRST-NAME CITY OR BOX NO. -------------------- -------------------- -------------------ANDERSON JENNY SAMUELSON MARTIN SALT LAKE CITY 3701 S. GEORGE MASON
DISPLX13 - DISPLAY (compare with WRITEX08 using WRITE) WRITEX08 - WRITE (compare with DISPLX13 using DISPLAY) DISPLX14 - DISPLAY (with AL, SF and nX) WRITEX09 - WRITE (in combination with AT END OF DATA)
248
Programming Guide
34
Groups
Use of Index Notation ..................................................................................................................... 250 Example of Index Notation in DISPLAY Statement ................................................................................ 250 Example of Index Notation in WRITE Statement .................................................................................. 251
249
Index Notation for Multiple-Value Fields and Periodic Groups The following topics are covered:
Output of Program DISPLX07: Note that a DISPLAY statement outputs multiple values of a multiple-value field underneath one another:
250
Programming Guide
Page PERSONNEL ID
1 NAME INCOME
04-11-11
14:15:54
CURRENCY ANNUAL BONUS CODE SALARY --------- -------------------- -------- ---------- ---------30020013 GARRET UKL UKL 4200 4150 0 7450 7350 6700 22000 20200 18700 0 0 0 0 0 0 0 0 0
30016112
TAILOR
20017600
PIETSCH
As a WRITE statement displays multiple values horizontally instead of vertically, this may cause a line overflow and a - possibly undesired - line advance. If you use only a single field within a periodic group (for example, SALARY) instead of the entire periodic group, and if you also insert a slash (/) to cause a line advance (as shown in the following example between NAME and JOB-TITLE), the report format becomes manageable.
Programming Guide
251
Index Notation for Multiple-Value Fields and Periodic Groups Output of Program WRITEX03:
Page
04-11-11
14:15:55
4200
4150
7450
7350
6700
22000
20200
18700
252
Programming Guide
35
Default Page Title .......................................................................................................................... 254 Suppress Page Title - NOTITLE Option .............................................................................................. 254 Define Your Own Page Title - WRITE TITLE Statement ......................................................................... 255 Logical Page and Physical Page ....................................................................................................... 258 Page Size - PS Parameter ............................................................................................................... 260 Page Advance .............................................................................................................................. 260 New Page with Title ....................................................................................................................... 263 Page Trailer - WRITE TRAILER Statement ......................................................................................... 264 Generating Blank Lines - SKIP Statement ........................................................................................... 266 AT TOP OF PAGE Statement ........................................................................................................... 268 AT END OF PAGE Statement ........................................................................................................... 269 Further Example ............................................................................................................................ 270
253
Page Titles, Page Breaks, Blank Lines The following topics are covered:
The above program produces the following output with default page title:
Page HELLO
04-12-14
13:19:33
** Example 'DISPLX20': DISPLAY (with NOTITLE) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 FIRST-NAME END-DEFINE * READ (5) EMPLOY-VIEW BY CITY FROM 'BOSTON' DISPLAY NOTITLE NAME FIRST-NAME CITY END-READ END
254
Programming Guide
NAME FIRST-NAME CITY -------------------- -------------------- -------------------SHAW STANWOOD CREMER PERREAULT COHEN LESLIE VERNON WALT BRENDA JOHN BOSTON BOSTON BOSTON BOSTON BOSTON
The above program produces the following output without page title:
HELLO
Specifying Text for Your Title Specifying Empty Lines after the Title Title Justification and/or Underlining Title with Page Number
Programming Guide
255
HELLO SKIP is not only available as part of the WRITE TITLE statement, but also as a stand-alone statement.
LEFT JUSTIFIED Causes the page trailer to be displayed left-justified. UNDERLINED Causes the title to be displayed underlined. The underlining runs the width of the line size (see also Natural profile and session parameter LS). By default, titles are underlined with a hyphen (-). However, with the UC session parameter you can specify another character to be used as underlining character (see Underlining Character for Titles and Headers).
256
Programming Guide
Page Titles, Page Breaks, Blank Lines The following example shows the effect of the LEFT JUSTIFIED and UNDERLINED options:
WRITE TITLE LEFT JUSTIFIED UNDERLINED 'THIS IS MY PAGE TITLE' SKIP 2 WRITE 'HELLO' END
HELLO
The WRITE TITLE statement is executed whenever a new page is initiated for the report.
** Example 'WTITLX01': WRITE TITLE (with *PAGE-NUMBER) ************************************************************************ DEFINE DATA LOCAL 1 VEHIC-VIEW VIEW OF VEHICLES 2 MAKE 2 YEAR 2 MAINT-COST (1) END-DEFINE * LIMIT 5 * READ VEHIC-VIEW END-ALL SORT BY YEAR USING MAKE MAINT-COST (1) DISPLAY NOTITLE YEAR MAKE MAINT-COST (1) AT BREAK OF YEAR MOVE 1 TO *PAGE-NUMBER NEWPAGE END-BREAK /* WRITE TITLE LEFT JUSTIFIED 'YEAR:' YEAR 15X 'PAGE' *PAGE-NUMBER END-SORT END
Programming Guide
257
YEAR: 1980 PAGE 1 YEAR MAKE MAINT-COST ----- -------------------- ---------1980 RENAULT 1980 RENAULT 1980 PEUGEOT 20000 20000 20000
258
Programming Guide
Note: If information you wish to appear at the bottom of the screen (for example, output created by a WRITE TRAILER or AT END OF PAGE statement) is output on the next screen instead, reduce the logical page size accordingly (with the session parameter PS, which is discussed below).
Programming Guide
259
At statement level:
DISPLAY (PS=nn) WRITE (PS=nn) WRITE TITLE (PS=nn) WRITE TRAILER (PS=nn) INPUT (PS=nn)
Page Advance
A page advance can be triggered by one of the following methods:
Page Advance Controlled by EJ Parameter Page Advance Controlled by EJECT or NEWPAGE Statements Eject/New Page when less than n Lines Left
260
Programming Guide
Page Advance without Title/Header on Next Page Page Advance with End/Top-of-Page Processing
Page Advance without Title/Header on Next Page The EJECT statement causes a page advance without a title or header line being generated on the next page. A new physical page is started without any top-of-page or end-of-page processing being performed (for example, no WRITE TRAILER or AT END OF PAGE, WRITE TITLE, AT TOP OF PAGE or *PAGE-NUMBER processing). The EJECT statement overrides the EJ parameter setting. Page Advance with End/Top-of-Page Processing The NEWPAGE statement causes a page advance with associated end-of-page and top-of-page processing. A trailer line will be displayed, if specified. A title line, either default or user-specified, will be displayed on the new page, unless the NOTITLE option has been specified in a DISPLAY or WRITE statement (as described above). If the NEWPAGE statement is not used, page advance is automatically controlled by the setting of the PS parameter; see Page Size - PS Parameter above).
Programming Guide
261
FORMAT PS=55 ... NEWPAGE WHEN LESS THAN 7 LINES LEFT ...
In this example, the page size is set to 55 lines. If only 6 or less lines are left on the current page at the time when the NEWPAGE statement is processed, the NEWPAGE statement is executed and a page advance occurs. If 7 or more lines are left, the NEWPAGE statement is not executed and no page advance occurs; the page advance then occurs depending on the session parameter PS (Page Size for Natural Reports), that is, after 55 lines. Example 2:
** Example 'NEWPAX02': NEWPAGE (in combination with EJECT and ** parameter PS) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 JOB-TITLE END-DEFINE * FORMAT PS=15 * READ (9) EMPLOY-VIEW BY CITY STARTING FROM 'BOSTON' AT START OF DATA EJECT WRITE /// 20T '%' (29) / 20T '%%' 47T '%%' / 20T '%%' 3X 'REPORT OF EMPLOYEES' 47T '%%' / 20T '%%' 3X ' SORTED BY CITY ' 47T '%%' / 20T '%%' 47T '%%' / 20T '%' (29) / NEWPAGE END-START AT BREAK OF CITY NEWPAGE WHEN LESS 3 LINES LEFT
262
Programming Guide
The following program illustrates the use of the session parameter PS (Page Size for Natural Reports) and the NEWPAGE statement. Moreover, the system variable *PAGE-NUMBER is used to display the current page number.
** Example 'NEWPAX01': NEWPAGE ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 CITY 2 DEPT END-DEFINE * FORMAT PS=20 READ (5) VIEWEMP BY CITY STARTING FROM 'M' DISPLAY NAME 'DEPT' DEPT 'LOCATION' CITY AT BREAK OF CITY NEWPAGE WITH TITLE LEFT JUSTIFIED 'EMPLOYEES BY CITY - PAGE:' *PAGE-NUMBER END-BREAK END-READ END
Output of Program NEWPAX01: Note the position of the page breaks and the title line:
Programming Guide
263
Page
04-11-11
14:15:54
NAME DEPT LOCATION -------------------- ------ -------------------FICKEN KELLOGG ALEXANDER TECH10 MADISON TECH10 MADISON SALE20 MADISON
Page 2:
EMPLOYEES BY CITY - PAGE: 2 NAME DEPT LOCATION -------------------- ------ -------------------DE JUAN DE LA MADRID SALE03 MADRID PROD01 MADRID
Page 3:
Specifying a Page Trailer Considering Logical Page Size Page Trailer Justification and/or Underlining
264
Programming Guide
The statement is executed when an end-of-page condition is detected, or as a result of a SKIP or NEWPAGE statement.
LEFT JUSTIFIED Causes the page trailer to be displayed left justified. UNDERLINED The underlining runs the width of the line size (see also Natural profile and session parameter LS). By default, titles are underlined with a hyphen (-). However, with the UC session parameter you can specify another character to be used as underlining character (see Underlining Character for Titles and Headers).
The following examples show the use of the LEFT JUSTIFIED and UNDERLINED options of the WRITE TRAILER statement:
Programming Guide
265
WRITE TRAILER LEFT JUSTIFIED UNDERLINED 'THIS IS THE END OF THE PAGE'
Example 2:
** Example 'WTITLX02': WRITE TITLE AND WRITE TRAILER ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 FIRST-NAME 2 ADDRESS-LINE (1) END-DEFINE * WRITE TITLE LEFT JUSTIFIED UNDERLINED *TIME 5X 'PEOPLE LIVING IN SALT LAKE CITY' 21X 'PAGE:' *PAGE-NUMBER / 15X 'AS OF' *DAT4E // * WRITE TRAILER UNDERLINED 'REGISTER OF' / 'SALT LAKE CITY' * READ (2) EMPLOY-VIEW WITH CITY = 'SALT LAKE CITY' DISPLAY NAME / FIRST-NAME 'HOME/CITY' CITY 'STREET/OR BOX NO.' ADDRESS-LINE (1) SKIP 1 END-READ END
266
Programming Guide
Page Titles, Page Breaks, Blank Lines Example 1 - SKIP in conjunction with WRITE and DISPLAY:
** Example 'SKIPX01': SKIP (in conjunction with WRITE and DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 FIRST-NAME 2 ADDRESS-LINE (1) END-DEFINE * WRITE TITLE LEFT JUSTIFIED UNDERLINED 'PEOPLE LIVING IN SALT LAKE CITY AS OF' *DAT4E 7X 'PAGE:' *PAGE-NUMBER SKIP 3 * READ (2) EMPLOY-VIEW WITH CITY = 'SALT LAKE CITY' DISPLAY NAME / FIRST-NAME CITY ADDRESS-LINE (1) SKIP 1 END-READ END
** Example 'SKIPX02': SKIP (in conjunction with DISPLAY VERT) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 JOB-TITLE END-DEFINE * READ (2) EMPLOY-VIEW WITH JOB-TITLE = 'SECRETARY' DISPLAY NOTITLE VERT NAME FIRST-NAME / CITY SKIP 3 END-READ * NEWPAGE * READ (2) EMPLOY-VIEW WITH JOB-TITLE = 'SECRETARY' DISPLAY NOTITLE NAME FIRST-NAME / CITY SKIP 3 END-READ END
Programming Guide
267
** Example 'ATTOPX01': AT TOP OF PAGE ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 MAR-STAT 2 BIRTH 2 CITY 2 JOB-TITLE 2 DEPT END-DEFINE * LIMIT 10 READ EMPLOY-VIEW BY PERSONNEL-ID FROM '20017000' DISPLAY NOTITLE (AL=10) NAME DEPT JOB-TITLE CITY 5X MAR-STAT 'DATE OF/BIRTH' BIRTH (EM=YY-MM-DD) /* AT TOP OF PAGE WRITE / '-BUSINESS INFORMATION-' 26X '-PRIVATE INFORMATION-' END-TOPPAGE END-READ END
268
Programming Guide
-BUSINESS INFORMATIONNAME DEPARTMENT CURRENT CITY CODE POSITION ---------- ---------- ---------- ---------CREMER MARKUSH GEE KUNEY NEEDHAM JACKSON PIETSCH PAUL HERZOG DEKKER TECH10 SALE00 TECH05 TECH10 TECH10 TECH10 MGMT10 MGMT10 TECH05 TECH10 ANALYST TRAINEE MANAGER DBA PROGRAMMER PROGRAMMER SECRETARY SECRETARY MANAGER DBA GREENVILLE LOS ANGELE CHAPEL HIL DETROIT CHATTANOOG ST LOUIS VISTA NORFOLK CHATTANOOG MOBILE
-PRIVATE INFORMATIONMARITAL DATE OF STATUS BIRTH ---------- -------S D M S S D M S S W 70-01-01 79-03-14 41-02-04 40-02-13 55-08-05 70-01-01 40-01-09 43-07-07 52-09-16 40-03-03
** Example 'ATENPX01': AT END OF PAGE (with system function available ** via GIVE SYSTEM FUNCTIONS in DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 JOB-TITLE 2 SALARY (1) END-DEFINE * READ (10) EMPLOY-VIEW BY PERSONNEL-ID = '20017000' DISPLAY NOTITLE GIVE SYSTEM FUNCTIONS
Programming Guide
269
CURRENT SALARY POSITION -------------------- ------------------------- ---------CREMER MARKUSH GEE KUNEY NEEDHAM JACKSON PIETSCH PAUL HERZOG DEKKER ANALYST TRAINEE MANAGER DBA PROGRAMMER PROGRAMMER SECRETARY SECRETARY MANAGER DBA 34000 22000 39500 40200 32500 33000 22000 23000 48500 48000
NAME
34270
Further Example
See the following example program:
270
Programming Guide
36
Column Headers
Default Column Headers ................................................................................................................. 272 Suppress Default Column Headers - NOHDR Option ............................................................................ 273 Define Your Own Column Headers .................................................................................................... 273 Combining NOTITLE and NOHDR .................................................................................................... 274 Centering of Column Headers - HC Parameter .................................................................................... 274 Width of Column Headers - HW Parameter ......................................................................................... 275 Filler Characters for Headers - Parameters FC and GC ......................................................................... 275 Underlining Character for Titles and Headers - UC Parameter ................................................................ 276 Suppressing Column Headers - Slash Notation .................................................................................... 277 Further Examples of Column Headers ............................................................................................... 278
271
** Example 'DISPLX01': DISPLAY ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * READ (3) VIEWEMP BY BIRTH DISPLAY PERSONNEL-ID NAME JOB-TITLE END-READ END
Output of Program DISPLX01: The above example program uses default headers and produces the following output.
Page
04-11-11
14:15:54
PERSONNEL NAME CURRENT ID POSITION --------- -------------------- ------------------------30020013 30016112 20017600 GARRET TAILOR PIETSCH TYPIST WAREHOUSEMAN SECRETARY
272
Programming Guide
Column Headers
** Example 'DISPLX08': DISPLAY (with column title in 'text') ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * READ (3) VIEWEMP BY BIRTH DISPLAY PERSONNEL-ID 'EMPLOYEE' NAME 'POSITION' JOB-TITLE END-READ END
Output of Program DISPLX08: The above program contains the header EMPLOYEE for the field NAME, and the header POSITION for the field JOB-TITLE; for the field PERSONNEL-ID, the default header is used. The program produces the following output:
Programming Guide
273
Column Headers
Page
04-11-11
14:15:54
PERSONNEL EMPLOYEE POSITION ID --------- -------------------- ------------------------30020013 30016112 20017600 GARRET TAILOR PIETSCH TYPIST WAREHOUSEMAN SECRETARY
The HC parameter can be used in a FORMAT statement to apply to the whole report, or it can be used in a DISPLAY statement at both statement level and element level.
DISPLAY (HC=L) PERSONNEL-ID NAME JOB-TITLE
274
Programming Guide
Column Headers
HW=OFF the width of a DISPLAY column is determined only by the length of the field. However, HW=OFF only applies to DISPLAY statements which do not create headers; that is, either a first DISPLAY statement with NOHDR option or a subsequent DISPLAY statement.
The HW parameter can be used in a FORMAT statement to apply to the entire report, or it can be used in a DISPLAY statement at both statement level and element (field) level.
** Example 'FORMAX01': FORMAT (with parameters FC, GC) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 INCOME (1:1) 3 CURR-CODE 3 SALARY 3 BONUS (1:1) END-DEFINE
Programming Guide
275
Column Headers
* FORMAT FC=* GC=$ * READ (3) VIEWEMP BY NAME DISPLAY NAME (FC==) INCOME (1) END-READ END
Page
04-11-11
14:15:54
========NAME======== $$$$$$$$$$$$INCOME$$$$$$$$$$$$ CURRENCY **ANNUAL** **BONUS*** CODE SALARY -------------------- -------- ---------- ---------ABELLAN ACHIESON ADAM PTA UKL FRA 1450000 10500 159980 0 0 23000
** Example 'FORMAX02': FORMAT (with parameter UC) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 BIRTH 2 JOB-TITLE END-DEFINE * FORMAT UC== * WRITE TITLE LEFT JUSTIFIED UNDERLINED 'EMPLOYEES REPORT' SKIP 1 READ (3) VIEWEMP BY BIRTH
276
Programming Guide
Column Headers
DISPLAY PERSONNEL-ID (UC=*) NAME JOB-TITLE END-READ END
In the above program, the UC parameter is specified at program level and at element (field) level: the underlining character specified with the FORMAT statement (=) applies for the whole report except for the field PERSONNEL-ID, for which a different underlining character (*) is specified. Output of Program FORMAX02:
EMPLOYEES REPORT =============================================================================== PERSONNEL NAME CURRENT ID POSITION ********* ==================== ========================= 30020013 30016112 20017600 GARRET TAILOR PIETSCH TYPIST WAREHOUSEMAN SECRETARY
In this case, the default column headers of all three fields will be displayed:
Programming Guide
277
Column Headers
Page
1 NAME
04-11-11
14:15:54
PERSONNEL CURRENT ID POSITION -------------------- --------- ------------------------ABELLAN ACHIESON ADAM ADKINSON ADKINSON ADKINSON 60008339 30000231 50005800 20008800 20009800 20011000 MAQUINISTA DATA BASE ADMINISTRATOR CHEF DE SERVICE PROGRAMMER DBA SALES PERSON
Example 2:
DISPLAY '/' NAME PERSONNEL-ID JOB-TITLE
In this case, the notation '/' causes the column header for the field NAME to be suppressed:
Page
04-11-11
14:15:54
MAQUINISTA DATA BASE ADMINISTRATOR CHEF DE SERVICE PROGRAMMER DBA SALES PERSON
DISPLX15 - DISPLAY (with FC, UC) DISPLX16 - DISPLAY (with '/', 'text', 'text/text')
278
Programming Guide
37
Overview of Field-Output-Relevant Parameters ................................................................................... 280 Leading Characters - LC Parameter .................................................................................................. 280 Insertion Characters - IC Parameter .................................................................................................. 281 Trailing Characters - TC Parameter ................................................................................................... 281 Output Length - AL and NL Parameters .............................................................................................. 282 Display Length for Output - DL Parameter .......................................................................................... 282 Sign Position - SG Parameter .......................................................................................................... 284 Identical Suppress - IS Parameter ..................................................................................................... 286 Zero Printing - ZP Parameter ........................................................................................................... 288 Empty Line Suppression - ES Parameter ............................................................................................ 288 Further Examples of Field-Output-Relevant Parameters ........................................................................ 290
279
Parameters to Influence the Output of Fields This chapter discusses the use of those Natural profile and/or session parameters which you can use to control the output format of fields. See also Output Reports and Workfiles (in the Operations documentation) for an overview of the Natural profile parameters that control various standard attributes used during the creation of Natural reports.
LC, IC and TC With these session parameters, you can specify characters that are to be displayed before or after a field or before a field value. AL and NL DL SG IS ZP ES With these session parameters, you can increase or reduce the output length of fields. With this session parameter, you can specify the default output length for an alphanumeric map field of format U. With this session parameter, you can determine whether negative values are to be displayed with or without a minus sign. With this session parameter, you can suppress the display of subsequent identical field values. With this profile and session parameter, you can determine whether field values of 0 are to be displayed or not. With this session parameter, you can suppress the display of empty lines generated by a DISPLAY or WRITE statement.
280
Programming Guide
Parameters to Influence the Output of Fields The LC parameter can be used with the following statements:
FORMAT DISPLAY
Programming Guide
281
They can be set at statement level and at element level. Note: If an edit mask is specified, it overrides an NL or AL specification. Edit masks are described in Edit Masks - EM Parameter.
282
Programming Guide
It can be set at statement level and at element level. The difference between the session parameters AL and DL is that AL defines the data length of a field whereas DL defines the number of columns which are used on the screen for displaying the field. The user can scroll in input fields to view the entire content of a field if the value specified with the DL session parameter is less than the length of the field data. Using the DL parameter with a length that is smaller than the length of the field is only recommended with the Web I/O Interface. When running Natural in a terminal emulation, scrolling in a field is not possible and so the effect is the same as using the AL parameter. Moreover, when changing the field contents, all characters which are beyond the display length will be lost. Note: DL is allowed for A-format fields as well. In conjunction with the Web I/O Interface, this would allow making the edit control size smaller than the content of a field. Example:
DEFINE DATA LOCAL 1 #U1 (U10) 1 #U2 (U10) END-DEFINE * #U1 := U'latintxt00' #U2 := U' * INPUT (AD=M) #U1 #U2 END
'
The above program produces the following output where the content of the field #U2 is incomplete:
#U1 latintxt00 #U2
When the session parameter DL is used with the field #U2 and is specified accordingly, the content of this field will be displayed correctly:
DEFINE DATA LOCAL 1 #U1 (U10) 1 #U2 (U10) END-DEFINE * #U1 := U'latintxt00' #U2 := U' *
'
Programming Guide
283
Result:
#U1 latintxt00 #U2
By default, SG=ON applies, which means that a sign position is allocated for numeric fields. If you specify SG=OFF, negative values in numeric fields will be output without a minus sign ().
It can be set at both statement level and element level. Note: If an edit mask is specified, it overrides an SG specification. Edit masks are described in Edit Masks - EM Parameter.
** Example 'FORMAX03': FORMAT (without FORMAT and compare with FORMAX04) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 SALARY (1:1) 2 BONUS (1:1,1:1) END-DEFINE * READ (5) VIEWEMP BY NAME STARTING FROM 'JONES'
284
Programming Guide
The above program contains no parameter settings and produces the following output:
Page
1 NAME FIRST-NAME
04-11-11
11:11:11
ANNUAL BONUS SALARY -------------------- -------------------- ---------- ---------JONES JONES JONES JONES JONES VIRGINIA MARSHA ROBERT LILLY EDWARD 46000 50000 31000 24000 37600 9000 0 0 0 0
** Example 'FORMAX04': FORMAT (with parameters AL, NL, LC, TC, IC and ** compare with FORMAX03) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 SALARY (1:1) 2 BONUS (1:1,1:1) END-DEFINE * FORMAT AL=10 NL=6 * READ (5) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME (LC=*) FIRST-NAME (TC=*) SALARY (1:1) (IC=$) BONUS (1:1,1:1) (LC=>) END-READ END
The above program produces the following output. Compare the layout of this output with that of the previous program to see the effect of the individual parameters:
Programming Guide
285
Page NAME
1 FIRST-NAME
04-11-11
11:11:11
ANNUAL BONUS SALARY ----------- ----------- -------- -------*JONES *JONES *JONES *JONES *JONES VIRGINIA MARSHA ROBERT LILLY EDWARD * * * * * $46000 $50000 $31000 $24000 $37600 > > > > > 9000 0 0 0 0
As you can see in the above example, any output length you specify with the AL or NL parameter does not include any characters specified with the LC, IC and TC parameters: the width of the NAME column, for example, is 11 characters - 10 for the field value (AL=10) plus 1 leading character. The width of the SALARY and BONUS columns is 8 characters - 6 for the field value (NL=6), plus 1 leading/inserted character, plus 1 sign position (because SG=ON applies).
By default, IS=OFF applies, which means that identical field values will be displayed. If IS=ON is specified, a value which is identical to the previous value of that field will not be displayed.
with a FORMAT statement to apply to the whole report, or in a DISPLAY or WRITE statement at both statement level and element level.
The effect of the parameter IS=ON can be suspended for one record by using the statement SUSPEND IDENTICAL SUPPRESS; see the Statements documentation for details. Compare the output of the following two example programs to see the effect of the IS parameter. In the second one, the display of identical values in the NAME field is suppressed.
286
Programming Guide
** Example 'FORMAX05': FORMAT (without parameter IS ** and compare with FORMAX06) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME FIRST-NAME END-READ END
Page
04-11-11
11:11:11
** Example 'FORMAX06': FORMAT (with parameter IS ** and compare with FORMAX05) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME END-DEFINE * FORMAT IS=ON * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME FIRST-NAME END-READ END
Programming Guide
287
Page
04-11-11
11:54:01
By default, ZP=ON applies, which means that one 0 (for numeric fields) or all zeros (for time fields) will be displayed for each field value that is zero. If you specify ZP=OFF, the display of each field value which is zero will be suppressed.
with a FORMAT statement to apply to the whole report, or in a DISPLAY or WRITE statement at both statement level and element level.
Compare the output of the following two example programs to see the effect of the parameters ZP and ES.
By default, ES=OFF applies, which means that lines containing all blank values will be displayed. If ES=ON is specified, a line resulting from a DISPLAY or WRITE statement which contains all blank values will not be displayed. This is particularly useful when displaying multiple-value fields or fields which are part of a periodic group if a large number of empty lines are likely to be produced.
with a FORMAT statement to apply to the whole report, or in a DISPLAY or WRITE statement at statement level.
288
Programming Guide
Parameters to Influence the Output of Fields Note: To achieve empty suppression for numeric values, in addition to ES=ON the parameter
ZP=OFF must also be set for the fields concerned in order to have null values turned into
blanks and thus not output either. Compare the output of the following two example programs to see the effect of the parameters ZP and ES.
** Example 'FORMAX07': FORMAT (without parameter ES and ZP ** and compare with FORMAX08) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 BONUS (1:2,1:1) END-DEFINE * READ (4) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME FIRST-NAME BONUS (1:2,1:1) END-READ END
Page
04-11-11
11:58:23
NAME FIRST-NAME BONUS -------------------- -------------------- ---------JONES JONES JONES JONES VIRGINIA MARSHA ROBERT LILLY 9000 6750 0 0 0 0 0 0
Programming Guide
289
** Example 'FORMAX08': FORMAT (with parameters ES and ZP ** and compare with FORMAX07) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 BONUS (1:2,1:1) END-DEFINE * FORMAT ES=ON * READ (4) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY NAME FIRST-NAME BONUS (1:2,1:1)(ZP=OFF) END-READ END
Page
04-11-11
11:59:09
NAME FIRST-NAME BONUS -------------------- -------------------- ---------JONES JONES JONES JONES VIRGINIA MARSHA ROBERT LILLY 9000 6750
DISPLX17 - DISPLAY (with NL, AL, IC, LC, TC) DISPLX18 - DISPLAY (using default settings for SF, AL, UC, LC, IC, TC and compare with DISPLX19) DISPLX19 - DISPLAY (with SF, AL, LC, IC, TC and compare with DISPLX18) SUSPEX01 - SUSPEND IDENTICAL SUPPRESS (in conjunction with parameters IS, ES, ZP in DISPLAY)
290
Programming Guide
SUSPEX02 - SUSPEND IDENTICAL SUPPRESS (in conjunction with parameters IS, ES, ZP in DISPLAY). Identical to SUSPEX01, but with IS=OFF. COMPRX03 - COMPRESS
Programming Guide
291
292
38
Use of EM Parameter ..................................................................................................................... 294 Edit Masks for Numeric Fields .......................................................................................................... 294 Edit Masks for Alphanumeric Fields ................................................................................................... 295 Length of Fields ............................................................................................................................. 295 Edit Masks for Date and Time Fields .................................................................................................. 296 Customizing Separator Character Displays ......................................................................................... 296 Examples of Edit Masks .................................................................................................................. 298 Further Examples of Edit Masks ....................................................................................................... 300
293
Edit Masks - EM Parameter This chapter describes how you can specify an edit mask for an alphanumeric or numeric field.
Use of EM Parameter
With the session parameter EM you can specify an edit mask for an alphanumeric or numeric field, that is, determine character by character the format in which the field values are to be output. Example:
DISPLAY NAME (EM=X^X^X^X^X^X^X^X^X^X)
In this example, each X represents one character of an alphanumeric field value to be displayed, and each ^ represents a blank. If displayed via the DISPLAY statement, the name JOHNSON would appear as follows:
J O H N S O N
at report level (in a FORMAT statement), at statement level (in a DISPLAY, WRITE, INPUT, MOVE EDITED or PRINT statement) or at element level (in a DISPLAY, WRITE or INPUT statement).
An edit mask specified with the session parameter EM will override a default edit mask specified for a field in the DDM; see Using the DDM Editor Screen, Specifying Extended Field Attributes. If EM=OFF is specified, no edit mask at all will be used. An edit mask specified at statement level will override an edit mask specified at report level. An edit mask specified at element level will override an edit mask specified at statement level.
A Z is used to indicate that the output position will be filled only if the available number is not zero. A decimal point is indicated with a period (.).
294
Programming Guide
Edit Masks - EM Parameter To the right of the decimal point, a Z must not be specified. Leading, trailing, and insertion characters - for example, sign indicators - can be added.
Length of Fields
It is important to be aware of the length of the field to which you assign an edit mask.
If the edit mask is longer than the field, this will yield unexpected results. If the edit mask is shorter than the field, the field output will be truncated to just those positions specified in the edit mask.
Examples: Assuming an alphanumeric field that is 12 characters long and the field value to be output is JOHNSON, the following edit masks will yield the following results:
Edit Mask
EM=X.X.X.X.X
Output
J.O.H.N.S
EM=****XXXXXX**** ****JOHNSO**
Programming Guide
295
Decimal Character
The Natural parameter DC (Decimal Character) is available to specify the character to be inserted in place of any characters used to represent the decimal separator (also called radix character) in edit masks. This parameter enables the users of a Natural program or application to choose any (special) character to separate the integer positions from the decimal positions of a numeric data item and enables, for example, U.S. shops to use the decimal point (.) and European shops to use the comma (,).
296
Programming Guide
Examples
A Natural program that is cataloged with parameter settings DC='.' and THSEP=ON uses the edit mask (EM=ZZ,ZZZ,ZZ9.99).
Parameter Settings at Runtime Displays as DC='.' and THSEPCH=',' DC=',' and THSEPCH='.' DC=',' and THSEPCH='/' DC=',' and THSEPCH=' ' DC=',' and THSEPCH='''' 1,234,567.89 1.234.567,89 1/234/567,89 1 234 567,89 1'234'567,89
Programming Guide
297
EM=MM.DD.YY * EM=HH.II.SS.T **
*
08.54.12.7 14.32.54.3
**
For further information about edit masks, see the session parameter EM in the Parameter Reference.
** Example 'EDITMX01': Edit mask (using default edit masks) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 SALARY (1:3) 2 CITY END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY 'N A M E' NAME / 'OCCUPATION' JOB-TITLE 'SALARY' SALARY (1:3) 'LOCATION' CITY SKIP 1 END-READ END
298
Programming Guide
Edit Masks - EM Parameter The output of this program shows the default edit masks available.
Page
04-11-11
14:15:54
N A M E SALARY LOCATION OCCUPATION ------------------------- ---------- -------------------JONES MANAGER 46000 TULSA 42300 39300 50000 MOBILE 46000 42700 31000 MILWAUKEE 29400 27600
JONES DIRECTOR
JONES PROGRAMMER
** Example 'EDITMX02': Edit mask (using EM) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 JOB-TITLE 2 SALARY (1:3) END-DEFINE * READ (3) VIEWEMP BY NAME STARTING FROM 'JONES' DISPLAY 'N A M E' NAME (EM=X^X^X^X^X^X^X^X^X^X^X^X^X^X^X) / FIRST-NAME (EM=...X(10)...) 'OCCUPATION' JOB-TITLE (EM=' ___ 'X(12)) 'SALARY' SALARY (1:3) (EM=' USD 'ZZZ,999) SKIP 1 END-READ END
Output of Program EDITMX02: Compare the output with that of the previous program (Example Program without EM Parameters) to see how the EM specifications affect the way the fields are displayed.
Programming Guide
299
Page
04-11-11
14:15:54
N A M E OCCUPATION SALARY FIRST-NAME ----------------------------- ---------------- ----------J O N E S ..VIRGINIA ___ MANAGER ... USD USD USD USD USD USD USD USD USD 46,000 42,300 39,300 50,000 46,000 42,700 31,000 29,400 27,600
J O N E S ..MARSHA
J O N E S ..ROBERT
EDITMX03 - Edit mask (different EM for alpha-numeric fields) EDITMX04 - Edit mask (different EM for numeric fields) EDITMX05 - Edit mask (EM for date and time system variables)
300
Programming Guide
39
Vertical Displays
Creating Vertical Displays ................................................................................................................ 302 Combining DISPLAY and WRITE ...................................................................................................... 302 Tab Notation - T*field ...................................................................................................................... 303 Positioning Notation x/y .................................................................................................................. 304 DISPLAY VERT Statement .............................................................................................................. 305 Further Example of DISPLAY VERT with WRITE Statement ................................................................... 311
301
Vertical Displays This chapter describes how you can combine the features of the statements DISPLAY and WRITE to produce vertical displays of field values.
You can use a combination of the statements DISPLAY and WRITE. You can use the VERT option of the DISPLAY statement.
** Example 'WRITEX04': WRITE (in combination with DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 CITY 2 DEPT END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'SAN FRANCISCO' DISPLAY NAME JOB-TITLE WRITE 22T 'DEPT:' DEPT SKIP 1 END-READ END
302
Programming Guide
Page
1 NAME
04-11-11
14:15:55
CURRENT POSITION -------------------- ------------------------KOLENCE MANAGER DEPT: TECH05 ANALYST DEPT: TECH10 SALES PERSON DEPT: SALE20
GOSDEN
WALLACE
** Example 'WRITEX05': WRITE (in combination with DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 DEPT 2 CITY END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'SAN FRANCISCO' DISPLAY NAME JOB-TITLE WRITE T*JOB-TITLE 'DEPT:' DEPT SKIP 1 END-READ END
Programming Guide
303
Page
1 NAME
04-11-11
14:15:55
CURRENT POSITION -------------------- ------------------------KOLENCE MANAGER DEPT: TECH05 ANALYST DEPT: TECH10 SALES PERSON DEPT: SALE20
GOSDEN
WALLACE
** Example 'WRITEX06': WRITE (with n/n) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 MIDDLE-I 2 ADDRESS-LINE (1:1) 2 CITY 2 ZIP END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' DISPLAY 'NAME AND ADDRESS' NAME WRITE 1/5 FIRST-NAME 1/30 MIDDLE-I 2/5 ADDRESS-LINE (1:1) 3/5 CITY
304
Programming Guide
Vertical Displays
3/30 ZIP / END-READ END
Page
04-11-11
14:15:55
NAME AND ADDRESS -------------------RUBIN SYLVIA 2003 SARAZEN PLACE NEW YORK WALLACE MARY 12248 LAUREL GLADE C NEW YORK KELLOGG HENRIETTA 1001 JEFF RYAN DR. NEWARK
L 10036
P 10036
S 19711
DISPLAY VERT without AS Clause DISPLAY VERT AS CAPTIONED and HORIZ DISPLAY VERT AS 'text' DISPLAY VERT AS 'text' CAPTIONED
Programming Guide
305
Vertical Displays
** Example 'DISPLX09': DISPLAY (without column title) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' DISPLAY VERT NAME FIRST-NAME / CITY SKIP 2 END-READ END
Output of Program DISPLX09: Note that all field values are displayed vertically underneath one another.
Page
04-11-11
14:15:54
306
Programming Guide
Vertical Displays
** Example 'DISPLX10': DISPLAY (with VERT as CAPTIONED and HORIZ clause) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 JOB-TITLE 2 SALARY (1:1) END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' DISPLAY VERT AS CAPTIONED NAME FIRST-NAME HORIZ JOB-TITLE SALARY (1:1) SKIP 1 END-READ END
Page
04-11-11
14:15:54
NAME CURRENT ANNUAL FIRST-NAME POSITION SALARY -------------------- ------------------------- ---------RUBIN SYLVIA WALLACE MARY KELLOGG HENRIETTA SECRETARY 17000
ANALYST
38000
DIRECTOR
52000
Programming Guide
307
Vertical Displays
** Example 'DISPLX11': DISPLAY (with VERT AS 'text' clause) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 JOB-TITLE 2 SALARY (1:1) END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' DISPLAY VERT AS 'EMPLOYEES' NAME FIRST-NAME HORIZ JOB-TITLE SALARY (1:1) SKIP 1 END-READ END
Page
1 EMPLOYEES
04-11-11
14:15:54
CURRENT ANNUAL POSITION SALARY -------------------- ------------------------- ---------RUBIN SYLVIA WALLACE MARY KELLOGG HENRIETTA SECRETARY 17000
ANALYST
38000
DIRECTOR
52000
308
Programming Guide
Vertical Displays
** Example 'DISPLX12': DISPLAY (with VERT AS 'text' CAPTIONED clause) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 JOB-TITLE 2 SALARY (1:1) END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' DISPLAY VERT AS 'EMPLOYEES' CAPTIONED NAME FIRST-NAME HORIZ JOB-TITLE SALARY (1:1) SKIP 1 END-READ END
Output of Program DISPLX12: This clause causes the default column headers (NAME and FIRST-NAME) to be placed before the field values:
Page
1 EMPLOYEES
04-11-11
14:15:54
CURRENT ANNUAL POSITION SALARY ------------------------------- ------------------------- ---------NAME RUBIN FIRST-NAME SYLVIA NAME WALLACE FIRST-NAME MARY NAME KELLOGG FIRST-NAME HENRIETTA SECRETARY 17000
ANALYST
38000
DIRECTOR
52000
Programming Guide
309
Vertical Displays
** Example 'WRITEX07': WRITE (with P*field) ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 CITY 2 NAME 2 JOB-TITLE 2 SALARY (1:1) 2 BONUS (1:1,1:1) END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'LOS ANGELES' DISPLAY NAME JOB-TITLE VERT AS 'INCOME' SALARY (1) BONUS (1,1) WRITE P*SALARY '***SALARY PLUS BONUS***' P*BONUS '(IN US DOLLARS)' SKIP 1 END-READ END
Page
1 NAME
04-11-11
14:15:55
CURRENT INCOME POSITION -------------------- ------------------------- ---------SMITH 0 0 ***SALARY PLUS BONUS*** (IN US DOLLARS) POORE JR SECRETARY 25000 0 ***SALARY PLUS BONUS***
310
Programming Guide
Vertical Displays
(IN US DOLLARS) PREPARATA MANAGER 46000 9000 ***SALARY PLUS BONUS*** (IN US DOLLARS)
Programming Guide
311
312
40
End of Statement, Program or Application Processing of Application Errors Conditional Processing - IF Statement Loop Processing Control Breaks Data Computation System Variables and System Functions Stack Processing of Date Information Text Notation User Comments Logical Condition Criteria Rules for Arithmetic Assignment Compilation Aspects
313
314
41
End of Statement ........................................................................................................................... 316 End of Program ............................................................................................................................. 316 End of Application .......................................................................................................................... 316
315
End of Statement
To explicitly mark the end of a statement, you can place a semicolon (;) between the statement and the next statement. This can be used to make the program structure clearer, but is not required.
End of Program
The END statement is used to mark the end of a Natural program, subprogram, external subroutine or helproutine. Every one of these objects must contain an END statement as the last statement. Every object may contain only one END statement.
End of Application
Ending the Execution of an Application by a STOP Statement
The STOP statement is used to terminate the execution of a Natural application. A STOP statement executed anywhere within an application immediately stops the execution of the entire application.
316
Programming Guide
42
Natural's Default Error Processing ..................................................................................................... 318 Application Specific Error Processing ................................................................................................. 318 Using an ON ERROR Statement Block .............................................................................................. 319 Using an Error Transaction Program .................................................................................................. 320 Error Processing Related Features .................................................................................................... 323
317
Processing of Application Errors This section discusses the two basic methods Natural offers for the handling of application errors: default processing and application-specific processing. Furthermore, it describes the options you have to enable the application specific error processing: coding an ON ERROR statement block within a programming object or using a separate error transaction program. Finally, this section gives an overview of the features that are provided to configure Natural's error processing behavior, to retrieve information on an error, to process or debug an application error. This document covers the following topics: For information on error handling in a Natural RPC environment, see Handling Errors in the Natural Remote Procedure Call documentation.
The information on the error is to be stored for further analysis by the application developer. The application execution is to be continued after error recovery, if possible.
318
Programming Guide
Because the execution of the affected Natural application object is terminated after an application error has occurred, the status of the pending database transactions may be influenced by actions which are triggered by the settings of the profile parameters ETEOP and ETIO. Therefore, further transaction handling (END TRANSACTION or BACKOUT TRANSACTION statement) has to be performed by the applications error processing. To enable the application specific error processing, you have the following options:
You may code an ON ERROR statement block within a programming object. You may use a separate error transaction program.
Error processing is assumed to be complete and application execution is resumed on the superior level.
FETCH
Programming Guide
319
Processing of Application Errors Natural stops the execution of the affected program, ends the application and returns to command input mode.
TERMINATE
The execution of the Natural application is stopped and also the Natural session is terminated. Error Processing Rules
If the execution of the ON ERROR statement block is not terminated by one of these statements, the error is percolated to the Natural object on the superior level for processing by an ON ERROR statement block that exists there. If none of the Natural objects on any of the superior levels contains an ON ERROR statement block, but if an error transaction program has been specified (as described in the next section), this error transaction program will receive control. If none of the Natural objects on any of the superior levels contains an ON ERROR statement block and no error transaction program has been specified there, Natural's default error processing will be performed as described above.
In the profile parameter ETA. If Natural Security is installed, within the Natural Security library profile; see Components of a Library Profile in the Natural Security documentation. Within a Natural object by assigning the name of the program which is to receive control in the event of an error condition as a value to the system variable *ERROR-TA, using an ASSIGN, COMPUTE or MOVE statement.
If you assign the name of an error transaction program to the system variable *ERROR-TA during the Natural session, this assignment supersedes an error transaction program specified using the profile parameter ETA. Regardless of whether you use the ETA profile parameter or assign a value to the system variable *ERROR-TA, the error transaction program names are not saved and restored by Natural for different levels of the call hierarchy. Therefore, if you assign a name to the system variable *ERROR-TA in a Natural object, the specified program will be invoked to process any error that occurs in the current Natural session after the assignment. On the one hand, if you specify an error transaction program by using the profile parameter ETA, an error transaction is defined for the complete Natural session without having the need for individual assignments in Natural objects. On the other hand, the method of assigning a program to the system variable *ERROR-TA provides more flexibility and, for example, allows you to have different error transaction programs in different application branches.
320
Programming Guide
Processing of Application Errors If the system variable *ERROR-TA is reset to blank, Natural's default error processing will be performed as described above. If an error transaction program is specified and an application error occurs, execution of the application is terminated, and the specified error transaction program receives control to perform the following actions:
Analyze the error; Log the error information; Terminate the Natural session; Continue the application execution by calling a program using the FETCH statement.
Because the error transaction program receives control in the same way as if it had been called from the command prompt, it is not possible to resume application execution in one of the Natural objects that were active at the time when the error occurred. If the Natural profile parameter SYNERR is set to ON and a syntax error occurs at compile time, the error transaction program will also receive control. An error transaction program must be located in the library to which you are currently logged on or in a current steplib library. When an error occurs, Natural executes a STACK TOP DATA statement and places the following information at the top of the stack:
Field Contents Natural error number Format/Length N4 if session parameter SG is set to OFF; N5 if
SG=ON
Number of the line where the error has occurred Status Code:
C L O R S
N4 A1
Command processing error (the line number will be zero) Logon processing error (the line number will be zero) Object (execution) time error Error on remote server (in conjunction with Natural RPC) Syntax error A8 N2
Name of the Natural object where the error has occurred Level number of the Natural object where the error has occurred
Programming Guide
321
Processing of Application Errors If the Natural profile parameter SYNERR is set to ON and a syntax error occurs at compile time, the level number will be zero, and the following information will be stacked in addition:
Field Contents Format/Length
Position of the offending item in the source line N3 Length of the offending item N3
This information can be retrieved in the error transaction program using an INPUT statement. Example:
DEFINE DATA LOCAL 1 #ERROR-NR (N5) 1 #LINE (N4) 1 #STATUS-CODE (A1) 1 #PROGRAM (A8) 1 #LEVEL (N2) 1 #POSITION-IN-LINE (N3) 1 #LENGTH-OF-ERRTOKEN (N3) END-DEFINE IF *DATA > 6 THEN /* SYNERR = ON and a syntax error occurred INPUT #ERROR-NR #LINE #STATUS-CODE #PROGRAM #LEVEL #POSITION-IN-LINE #LENGTH-OF-ERRTOKEN ELSE INPUT /* other error #ERROR-NR #LINE #STATUS-CODE #PROGRAM #LEVEL END-IF WRITE #STATUS-CODE * DECIDE ON FIRST VALUE OF STATUS-CODE * ... /* process error * END-DECIDE END
322
Programming Guide
Processing of Application Errors Some of the information placed on top of the stack is equivalent to the contents of several system variables that are available in an ON ERROR statement block:
Field Contents Natural error number Number of the line where the error has occurred Name of the Natural object where the error has occurred Equivalent System Variable in ON ERROR Statement Block
*ERROR-NR *ERROR-LINE *PROGRAM
Level number of the program where the error has occurred *LEVEL
Rules under Natural Security If Natural Security is installed, the additional rules for the processing of logon errors apply. For further information, see Transactions in the Natural Security documentation.
Enable you to configure Naturals error processing behavior; Help you in retrieving information about errors that have occurred; Support you in processing these errors; Support you in debugging application errors.
Profile parameters System variables Terminal Commands System commands Application programming interfaces
Programming Guide
323
Processing of Application Errors Profile Parameters The following profile parameters have an influence on the behavior of Natural in the event of an error:
Profile Parameter Purpose
CPCVERR DBGERR ETA ETEOP ETIO RCFIND RCGET SYNERR
Conversion Error Automatic Start of Debugger at Runtime Error Error Transaction Program Issue END TRANSACTION at End of Program Issue END TRANSACTION upon Terminal I/O Handling of Response Code 113 for FIND Statement Handling of Response Code 113 for GET Statement Control of Syntax Errors
System Variables The following application related system variables can be used to locate an error or to obtain/specify the name of the program which is to receive control in the event of an error condition:
System Variable Content
*ERROR-LINE Source-code line number of the statement that caused an error.
See Example 1.
*ERROR-NR *ERROR-TA
Error number of the error which caused an ON ERROR condition to be entered. Name of the program which is to receive control in the event of an error condition. See Example 2.
*LEVEL
Level number of the Natural object where the error has occurred. Name of the Natural object that is currently being executed. See Example 1.
*LIBRARY-ID Name of the library to which the user is currently logged on. *PROGRAM
324
Programming Guide
Example 2:
... *ERROR-TA := 'ERRORTA1' /* from now on, program ERRORTA1 will be invoked /* to process application errors ... MOVE 'ERRORTA2' TO *ERROR-TA /* change error transaction program to ERRORTA2 ...
For further information on these system variables, see the corresponding sections in the System Variables documentation. Terminal Commands The following terminal command has an influence on the behavior of Natural in the event of an error:
Terminal Command Purpose
%E=
Programming Guide
325
Processing of Application Errors System Commands The following system commands provide additional information on an error situation or invoke the utilities for debugging or logging database calls:
System Command Purpose
LASTMSG RPCERR TECH TEST TEST DBLOG
Display additional information on the error situation which has occurred last. Display the last Natural error number and message if it was Natural RPC related. Display technical and other information about your Natural session, for example, information on the last error that occurred. Invoke the debugger. Invoke the DBLOG utility, which is used for logging database calls.
Application Programming Interfaces The following application programming interfaces (APIs) are generally available for getting additional information on an error situation or to install an error transaction.
API Purpose
USR0040N Get type of last error USR1016N Display error level for copycode USR1037N Information about Natural ABEND data USR1041N Sample error transaction program (*ERROR-TA) USR2001N Read information about last error USR2006N Get detailed message information USR2007N Set/get RPC default server information USR2010N Display DB error information USR2026N Get TECH information USR2030N Read dynamic error parts :1:,... USR2034N Read system or user error message text from either FNAT or FUSER USR3320N Find user short error message from FNAT or FUSER USR4214N Display program level information
For further information, see SYSEXT - Natural Application Programming Interfaces in the Utilities documentation.
326
Programming Guide
Processing of Application Errors For SQL calls, the following application programming interfaces are available:
API
NDBERR
Purpose Provides diagnostic information on the most recently executed SQL call.
NDBNOERR Suppresses Natural's error handling for errors caused by the next SQL call.
Interface Subprograms in the Natural for DB2 documentation. Interface Subprograms in the Natural for SQL/DS documentation. Interface Subprograms in the Natural SQL Gateway documentation.
Programming Guide
327
328
43
329
Conditional Processing - IF Statement With the IF statement, you define a logical condition, and the execution of the statement attached to the IF statement then depends on that condition.
Structure of IF Statement
The IF statement contains three components:
IF In the IF clause, you specify the logical condition which is to be met.
THEN In the THEN clause you specify the statement(s) to be executed if this condition is met. ELSE In the (optional) ELSE clause, you can specify the statement(s) to be executed if this condition is not met.
Note: If you wish a certain processing to be performed only if the IF condition is not met, you can specify the clause THEN IGNORE. The IGNORE statement causes the IF condition to be ignored if it is met. Example 1:
** Example 'IFX01': IF ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 BIRTH 2 CITY 2 SALARY (1:1) END-DEFINE * LIMIT 7 READ MYVIEW BY CITY STARTING FROM 'C' IF SALARY (1) LT 40000 THEN WRITE NOTITLE '*****' NAME 30X 'SALARY LT 40000' ELSE DISPLAY NAME BIRTH (EM=YYYY-MM-DD) SALARY (1) END-IF END-READ END
330
Programming Guide
Conditional Processing - IF Statement The IF statement block in the above program causes the following conditional processing to be performed:
IF
the salary is less than 40000, THEN the WRITE statement is to be executed;
otherwise (ELSE), that is, if the salary is 40000 or more, the DISPLAY statement is to be executed.
DATE ANNUAL OF SALARY BIRTH -------------------- ---------- ---------***** KEEN ***** FORRESTER ***** JONES ***** MELKANOFF DAVENPORT GEORGES ***** FULLERTON SALARY SALARY SALARY SALARY 1948-12-25 1949-10-26 42000 182800 SALARY LT 40000 LT LT LT LT 40000 40000 40000 40000
NAME
Example 2:
** Example 'IFX03': IF ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 BONUS (1,1) 2 SALARY (1) * 1 #INCOME (N9) 1 #TEXT (A26) END-DEFINE * WRITE TITLE '-- DISTRIBUTION OF CATALOGS I AND II --' / * READ (3) EMPLOY-VIEW BY CITY = 'SAN FRANSISCO' COMPUTE #INCOME = BONUS(1,1) + SALARY(1) /* IF #INCOME > 40000 MOVE 'CATALOGS I AND II' TO #TEXT ELSE MOVE 'CATALOG I' TO #TEXT END-IF /* DISPLAY NAME 5X 'SALARY' SALARY(1) / BONUS(1,1)
Programming Guide
331
56000 0 ---------INCOME: 56000 =================== 9150 0 ---------INCOME: 9150 =================== 13500 600 ---------INCOME: 14100 ===================
CATALOGS I AND II
RICHMOND
CATALOG I
MONKTON
CATALOG I
Nested IF Statements
It is possible to use various nested IF statements; for example, you can make the execution of a THEN clause dependent on another IF statement which you specify in the THEN clause.
332
Programming Guide
** Example 'IFX02': IF (two IF statements nested) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 SALARY (1:1) 2 BIRTH 2 PERSONNEL-ID 1 MYVIEW2 VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE * 1 #BIRTH (D) END-DEFINE * MOVE EDITED '19450101' TO #BIRTH (EM=YYYYMMDD) * LIMIT 20 FND1. FIND MYVIEW WITH CITY = 'BOSTON' SORTED BY NAME IF SALARY (1) LESS THAN 20000 WRITE NOTITLE '*****' NAME 30X 'SALARY LT 20000' ELSE IF BIRTH GT #BIRTH FIND MYVIEW2 WITH PERSONNEL-ID = PERSONNEL-ID (FND1.) DISPLAY (IS=ON) NAME BIRTH (EM=YYYY-MM-DD) SALARY (1) MAKE (AL=8 IS=OFF) END-FIND END-IF END-IF SKIP 1 END-FIND END
DATE ANNUAL MAKE OF SALARY BIRTH -------------------- ---------- ---------- -------***** COHEN CREMER ***** FLEMING 1972-12-14 20000 FORD SALARY LT 20000 SALARY LT 20000
NAME
Programming Guide
333
1950-05-12
1946-09-08
334
Programming Guide
44
Loop Processing
Use of Processing Loops ................................................................................................................ 336 Limiting Database Loops ................................................................................................................. 336 Limiting Non-Database Loops - REPEAT Statement ............................................................................. 338 Example of REPEAT Statement ........................................................................................................ 339 Terminating a Processing Loop - ESCAPE Statement ........................................................................... 340 Loops Within Loops ....................................................................................................................... 340 Example of Nested FIND Statements ................................................................................................. 341 Referencing Statements within a Program .......................................................................................... 342 Example of Referencing with Line Numbers ........................................................................................ 344 Example with Statement Reference Labels ......................................................................................... 344
335
Loop Processing A processing loop is a group of statements which are executed repeatedly until a stated condition has been satisfied, or as long as a certain condition prevails.
Database processing loops are those created automatically by Natural to process data selected from a database as a result of a READ, FIND or HISTOGRAM statement. These statements are described in the section Database Access. Non-database processing loops are initiated by the statements REPEAT, FOR, CALL FILE, CALL LOOP, SORT, and READ WORK FILE.
More than one processing loop may be active at the same time. Loops may be embedded or nested within other loops which remain active (open). A processing loop must be explicitly closed with a corresponding END-... statement (for example, END-REPEAT, END-FOR) The SORT statement, which invokes the sort program of the operating system, closes all active processing loops and initiates a new processing loop.
Possible Ways of Limiting Database Loops LT Session Parameter LIMIT Statement Limit Notation
336
Programming Guide
Loop Processing
using the session parameter LT, using a LIMIT statement, or using a limit notation in a READ/FIND/HISTOGRAM statement itself.
LT Session Parameter
With the system command GLOBALS, you can specify the session parameter LT, which limits the number of records which may be read in a database processing loop. Example:
GLOBALS LT=100
This limit applies to all READ, FIND and HISTOGRAM statements in the entire session.
LIMIT Statement
In a program, you can use the LIMIT statement to limit the number of records which may be read in a database processing loop. Example:
LIMIT 100
The LIMIT statement applies to the remainder of the program unless it is overridden by another LIMIT statement or limit notation.
Limit Notation
With a READ, FIND or HISTOGRAM statement itself, you can specify the number of records to be read in parentheses immediately after the statement name.
Programming Guide
337
This limit notation overrides any other limit in effect, but applies only to the statement in which it is specified.
in an UNTIL clause, the REPEAT loop will continue until the logical condition is met; in a WHILE clause, the REPEAT loop will continue as long as the logical condition remains true.
If you specify no logical condition, the REPEAT loop must be exited with one of the following statements:
ESCAPE
terminates the execution of the processing loop and continues processing outside the loop (see below). stops the execution of the entire Natural application. stops the execution of the Natural application and also ends the Natural session.
STOP
TERMINATE
338
Programming Guide
Loop Processing
Page
1 NAME
04-11-11
14:15:54
ANNUAL #PAY1 SALARY -------------------- ---------- --------ADKINSON 34500 37950 41745 36850 40535 39600 43560 40700 37950 41745
33500
36000
AFANASSIEV ALEXANDER
37000 34500
Programming Guide
339
Loop Processing
ESCAPE BOTTOM is used to continue processing with the first statement following the processing
loop. You can specify several ESCAPE statements within the same processing loop. For further details and examples of the ESCAPE statement, see the Statements documentation.
340
Programming Guide
Loop Processing
** Example 'FINDX06': FIND (two FIND statements nested) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 PERSONNEL-ID 1 VEH-VIEW VIEW OF VEHICLES 2 MAKE 2 PERSONNEL-ID END-DEFINE * FND1. FIND EMPLOY-VIEW WITH CITY = 'NEW YORK' OR = 'BEVERLEY HILLS' FIND (1) VEH-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (FND1.) DISPLAY NOTITLE NAME CITY MAKE END-FIND END-FIND END
The above program selects data from multiple files. The outer FIND loop selects from the EMPLOYEES file all persons who live in New York or Beverley Hills. For each record selected in the outer loop, the inner FIND loop is entered, selecting the car data of those persons from the VEHICLES file. Output of Program FINDX06:
NAME CITY MAKE -------------------- -------------------- -------------------RUBIN OLLE WALLACE JONES SPEISER NEW YORK BEVERLEY HILLS NEW YORK BEVERLEY HILLS BEVERLEY HILLS FORD GENERAL MOTORS MAZDA FORD GENERAL MOTORS
Programming Guide
341
Loop Processing
Referring to previous statements in a program in order to specify processing over a particular range of data. Overriding Natural's default referencing. Documenting.
Any Natural statement which causes a processing loop to be initiated and/or causes data elements in a database to be accessed can be referenced, for example:
READ FIND HISTOGRAM SORT REPEAT FOR
When multiple processing loops are used in a program, reference notation is used to uniquely identify the particular database field to be processed by referring back to the statement that originally accessed that field in the database. If a field can be referenced in such a way, this is indicated in the Referencing Permitted column of the Operand Definition Table in the corresponding statement description (in the Statements documentation). See also User-Defined Variables, Referencing of Database Fields Using (r) Notation. In addition, reference notation can be specified in some statements. For example:
AT START OF DATA AT END OF DATA AT BREAK ESCAPE BOTTOM
Without reference notation, an AT START OF DATA, AT END OF DATA or AT BREAK statement will be related to the outermost active READ, FIND, HISTOGRAM, SORT or READ WORK FILE loop. With reference notation, you can relate it to another active processing loop. If reference notation is specified with an ESCAPE BOTTOM statement, processing will continue with the first statement following the processing loop identified by the reference notation.
342
Programming Guide
Loop Processing Statement reference notation may be specified in the form of a statement reference label or a sourcecode line number.
Statement reference label A statement reference label consists of several characters, the last of which must be a period (.). The period serves to identify the entry as a label. A statement that is to be referenced is marked with a label by placing the label at the beginning of the line that contains the statement. For example:
In the statement that references the marked statement, the label is placed in parentheses at the location indicated in the statement's syntax diagram (as described in the Statements documentation). For example:
Source-code line number If source-code line numbers are used for referencing, they must be specified as 4-digit numbers (leading zeros must not be omitted) and in parentheses. For example:
In a statement where the label/line number relates a particular field to a previous statement, the label/line number is placed in parentheses after the field name. For example:
Line numbers and labels can be used interchangeably. See also User-Defined Variables, Referencing of Database Fields Using (r) Notation.
Programming Guide
343
Loop Processing
0010 0020 0030 0040 0050 0060 0070 0080 0090 0100 0110 0120 0130 0140 0150 0160 0170 0180 0190 0200 0210 0220 0230 0240
** Example 'LABELX01': Labels for READ and FIND loops (line numbers) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW1 VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 PERSONNEL-ID 1 MYVIEW2 VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 15 READ MYVIEW1 BY NAME STARTING FROM 'JONES' FIND MYVIEW2 WITH PERSONNEL-ID = PERSONNEL-ID (0140) IF NO RECORDS FOUND MOVE '***NO CAR***' TO MAKE END-NOREC DISPLAY NOTITLE NAME (0140) (IS=ON) FIRST-NAME (0140) (IS=ON) MAKE (0150) END-FIND /* (0150) END-READ /* (0140) END
344
Programming Guide
Loop Processing It is identical to the previous program, except that labels are used for referencing instead of line numbers.
** Example 'LABELX02': Labels for READ and FIND loops (user labels) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW1 VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 PERSONNEL-ID 1 MYVIEW2 VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 15 RD. READ MYVIEW1 BY NAME STARTING FROM 'JONES' FD. FIND MYVIEW2 WITH PERSONNEL-ID = PERSONNEL-ID (RD.) IF NO RECORDS FOUND MOVE '***NO CAR***' TO MAKE END-NOREC DISPLAY NOTITLE NAME (RD.) (IS=ON) FIRST-NAME (RD.) (IS=ON) MAKE (FD.) END-FIND /* (FD.) END-READ /* (RD.) END
NAME FIRST-NAME MAKE -------------------- -------------------- -------------------JONES VIRGINIA MARSHA ROBERT LILLY EDWARD LAUREL KEVIN GREGORY MANFRED DANIEL GABRIEL ERNST JEREMY REINER HEIKE CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD MG GENERAL MOTORS GENERAL MOTORS DATSUN FORD ***NO CAR*** RENAULT ***NO CAR*** ***NO CAR*** ***NO CAR*** ***NO CAR*** ***NO CAR***
Programming Guide
345
346
45
Control Breaks
Use of Control Breaks ..................................................................................................................... 348 AT BREAK Statement ..................................................................................................................... 348 Automatic Break Processing ............................................................................................................ 353 Example of System Functions with AT BREAK Statement ...................................................................... 355 Further Example of AT BREAK Statement .......................................................................................... 356 BEFORE BREAK PROCESSING Statement ....................................................................................... 356 Example of BEFORE BREAK PROCESSING Statement ....................................................................... 356 User-Initiated Break Processing - PERFORM BREAK PROCESSING Statement ........................................ 357 Example of PERFORM BREAK PROCESSING Statement ..................................................................... 359
347
Control Breaks This chapter describes how the execution of a statement can be made dependent on a control break, and how control breaks can be used for the evaluation of Natural system functions.
AT BREAK Statement
With the statement AT BREAK, you specify the processing which is to be performed whenever a control break occurs, that is, whenever the value of a control field which you specify with the AT BREAK statement changes. As a control field, you can use a database field or a user-defined variable. The following topics are covered below:
Control Break Based on a Database Field Control Break Based on a User-Defined Variable Multiple Control Break Levels
In this example, the control field is the database field DEPT; if the value of the field changes, for example, FROM SALE01 to SALE02, the statements specified in the AT BREAK statement would be executed.
348
Programming Guide
Control Breaks Instead of an entire field, you can also use only part of a field as a control field. With the slash-n-slash notation /n/, you can determine that only the first n positions of a field are to be checked for a change in value. Example:
... AT BREAK OF DEPT /4/ statements END-BREAK ...
In this example, the specified statements would only be executed if the value of the first 4 positions of the field DEPT changes, for example, FROM SALE to TECH; if, however, the field value changes from SALE01 to SALE02, this would be ignored and no AT BREAK processing performed. Example:
** Example 'ATBREX01': AT BREAK OF (with database field) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 COUNTRY 2 JOB-TITLE 2 SALARY (1:1) END-DEFINE * READ (5) MYVIEW BY CITY WHERE COUNTRY = 'USA' DISPLAY CITY (AL=9) NAME 'POSITION' JOB-TITLE 'SALARY' SALARY(1) /* AT BREAK OF CITY WRITE / OLD(CITY) (EM=X^X^X^X^X^X^X^X^X^X^X^) 5X 'AVERAGE:' T*SALARY AVER(SALARY(1)) // COUNT(SALARY(1)) 'RECORDS FOUND' / END-BREAK /* AT END OF DATA WRITE 'TOTAL (ALL RECORDS):' T*SALARY(1) TOTAL(SALARY(1)) END-ENDDATA END-READ END
In the above program, the first WRITE statement is executed whenever the value of the field CITY changes. In the AT BREAK statement, the Natural system functions OLD, AVER and COUNT are evaluated (and output in the WRITE statement). Programming Guide 349
Control Breaks In the AT END OF DATA statement, the Natural system function TOTAL is evaluated. Output of Program ATBREX01:
Page
04-12-14
14:07:26
CITY NAME POSITION SALARY --------- -------------------- ------------------------- ---------AIKEN A I K E N 1 RECORDS FOUND ALBUQUERQ ALBUQUERQ ALBUQUERQ ALBUQUERQ HAMMOND ROLLING FREEMAN LINCOLN SECRETARY MANAGER MANAGER ANALYST AVERAGE: 22000 34000 34000 41000 32750 SENKO PROGRAMMER AVERAGE: 31500 31500
162500
** Example 'ATBREX02': AT BREAK OF (with user-defined variable and ** in conjunction with BEFORE BREAK PROCESSING) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 CITY 2 COUNTRY 2 JOB-TITLE 2 SALARY (1:1) * 1 #LOCATION (A20) END-DEFINE * READ (5) MYVIEW BY CITY WHERE COUNTRY = 'USA' BEFORE BREAK PROCESSING COMPRESS CITY 'USA' INTO #LOCATION
350
Programming Guide
Control Breaks
END-BEFORE DISPLAY #LOCATION 'POSITION' JOB-TITLE 'SALARY' SALARY (1) /* AT BREAK OF #LOCATION SKIP 1 END-BREAK END-READ END
Page
04-12-14
14:08:36
#LOCATION POSITION SALARY -------------------- ------------------------- ---------AIKEN USA ALBUQUERQUE ALBUQUERQUE ALBUQUERQUE ALBUQUERQUE USA USA USA USA PROGRAMMER SECRETARY MANAGER MANAGER ANALYST 31500 22000 34000 34000 41000
** Example 'ATBREX03': AT BREAK OF (two statements in combination) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 JOB-TITLE 2 DEPT 2 SALARY (1:1) 2 CURR-CODE (1:1) END-DEFINE *
Programming Guide
351
Control Breaks
READ MYVIEW BY DEPT STARTING FROM 'SALE40' ENDING AT 'TECH10' WHERE SALARY(1) GT 47000 AND CURR-CODE(1) = 'USD' /* AT BREAK OF DEPT WRITE '*** LOWEST BREAK LEVEL ***' / END-BREAK AT BREAK OF DEPT /4/ WRITE '*** HIGHEST BREAK LEVEL ***' END-BREAK /* DISPLAY DEPT NAME 'POSITION' JOB-TITLE END-READ END
Page
04-12-14
14:09:20
DEPARTMENT NAME POSITION CODE ---------- -------------------- ------------------------TECH05 TECH05 TECH05 *** LOWEST HERZOG LAWLER MEYER BREAK LEVEL *** MANAGER MANAGER MANAGER
TECH10 DEKKER *** LOWEST BREAK LEVEL *** *** HIGHEST BREAK LEVEL ***
DBA
In the following program, one blank line is output whenever the value of the field DEPT changes; and whenever the value in the first 4 positions of DEPT changes, a record count is carried out by evaluating the system function COUNT.
** Example 'ATBREX04': AT BREAK OF (two statements in combination) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 DEPT 2 REDEFINE DEPT 3 #GENDEP (A4) 2 NAME 2 SALARY (1) END-DEFINE * WRITE TITLE '** PERSONS WITH SALARY > 30000, SORTED BY DEPARTMENT **' /
352
Programming Guide
Control Breaks
LIMIT 9 READ MYVIEW BY DEPT FROM 'A' WHERE SALARY(1) > 30000 DISPLAY 'DEPT' DEPT NAME 'SALARY' SALARY(1) /* AT BREAK OF DEPT SKIP 1 END-BREAK AT BREAK OF DEPT /4/ WRITE COUNT(SALARY(1)) 'RECORDS FOUND IN:' OLD(#GENDEP) / END-BREAK END-READ END
** PERSONS WITH SALARY > 30000, SORTED BY DEPARTMENT ** DEPT NAME SALARY ------ -------------------- ---------ADMA01 ADMA01 ADMA01 ADMA01 ADMA01 JENSEN PETERSEN MORTENSEN MADSEN BUHL 180000 105000 320000 149000 642000 391500 162900 234000
ADMA02 HERMANSEN ADMA02 PLOUG ADMA02 HANSEN 8 RECORDS FOUND IN: ADMA COMP01 HEURTEBISE 1 RECORDS FOUND IN: COMP
168800
Programming Guide
353
Control Breaks
READ WORK FILE
The value of the control field specified with the AT BREAK statement is checked only for records which satisfy the selection criteria of both the WITH clause and the WHERE clause. Natural system functions (AVER, MAX, MIN, etc.) are evaluated for each record after all statements within the processing loop have been executed. System functions are not evaluated for any record which is rejected by WHERE criteria. The figure below illustrates the flow logic of automatic break processing.
354
Programming Guide
Control Breaks
** Example 'ATBREX05': AT BREAK OF (with system functions) ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 SALARY (1:1) 2 CURR-CODE (1:1) END-DEFINE * LIMIT 3 READ MYVIEW BY CITY = 'SALT LAKE CITY' DISPLAY NOTITLE CITY NAME 'SALARY' SALARY(1) 'CURRENCY' CURR-CODE(1) /* AT BREAK OF CITY WRITE / OLD(CITY) (EM=X^X^X^X^X^X^X^X^X^X^X^X^X^X^X) 31T ' - MINIMUM:' MIN(SALARY(1)) CURR-CODE(1) / 31T ' - AVERAGE:' AVER(SALARY(1)) CURR-CODE(1) / 31T ' - MAXIMUM:' MAX(SALARY(1)) CURR-CODE(1) / 31T ' SUM:' SUM(SALARY(1)) CURR-CODE(1) / 33T COUNT(SALARY(1)) 'RECORDS FOUND' / END-BREAK /* AT END OF DATA WRITE 22T 'TOTAL (ALL RECORDS):' T*SALARY TOTAL(SALARY(1)) CURR-CODE(1) END-ENDDATA END-READ END
CITY NAME SALARY CURRENCY -------------------- -------------------- ---------- -------SALT LAKE CITY SALT LAKE CITY S A L T L A K E ANDERSON SAMUELSON C I T Y - MINIMUM: - AVERAGE: - MAXIMUM: 50000 USD 24000 USD 24000 USD 37000 USD 50000 USD
Programming Guide
355
Control Breaks
SUM: 74000 USD 2 RECORDS FOUND 60000 USD - MINIMUM: 60000 USD - AVERAGE: 60000 USD - MAXIMUM: 60000 USD SUM: 60000 USD 1 RECORDS FOUND TOTAL (ALL RECORDS): 134000 USD
SAN DIEGO S A N D I E G O
GEE
ATBREX06 - AT BREAK OF (comparing NMIN, NAVER, NCOUNT with MIN, AVER, COUNT)
356
Programming Guide
Control Breaks
BEFORE BREAK PROCESSING COMPUTE #INCOME = SALARY(1) + BONUS(1,1) END-BEFORE /* DISPLAY NOTITLE NAME FIRST-NAME (AL=10) 'ANNUAL/INCOME' #INCOME 'SALARY' SALARY(1) (LC==) / '+ BONUS' BONUS(1,1) (IC=+) AT BREAK OF #INCOME WRITE T*#INCOME '-'(24) END-BREAK END-READ END
ANNUAL SALARY INCOME + BONUS -------------------- ---------- ------------ ----------BACHMANN HANS 52800 +4000 -----------------------81000 = 74400 +6600 -----------------------52650 = 48600 +4050 -----------------------152700 = 129700 +23000 -----------------------198500 = 188000 +10500 -----------------------56800 =
NAME
FIRST-NAME
BAECKER
JOHANNES
BAECKER
KARL
BAGAZJA
MARJAN
BAILLET
PATRICK
Programming Guide
357
Control Breaks Immediately after the PERFORM BREAK PROCESSING, you specify one or more AT BREAK statement blocks:
... PERFORM BREAK PROCESSING AT BREAK OF field1 statements END-BREAK AT BREAK OF field2 statements END-BREAK ...
When a PERFORM BREAK PROCESSING is executed, Natural checks if a break has occurred; that is, if the value of the specified control field has changed; and if it has, the specified statements are executed. With PERFORM BREAK PROCESSING, system functions are evaluated before Natural checks if a break has occurred. The following figure illustrates the flow logic of user-initiated break processing:
358
Programming Guide
Control Breaks
Programming Guide
359
Control Breaks
AT BREAK OF DEPT /* <- automatic break processing SKIP 1 WRITE 'SUMMARY FOR ALL SALARIES ' 'SUM:' SUM(SALARY(1)) 'TOTAL:' TOTAL(SALARY(1)) ADD 1 TO #CNTL END-BREAK /* IF SALARY (1) GREATER THAN 100000 OR BREAK #CNTL PERFORM BREAK PROCESSING /* <- user-initiated break processing AT BREAK OF #CNTL WRITE 'SUMMARY FOR SALARY GREATER 100000' 'SUM:' SUM(SALARY(1)) 'TOTAL:' TOTAL(SALARY(1)) END-BREAK END-IF /* IF SALARY (1) GREATER THAN 150000 OR BREAK #CNTL PERFORM BREAK PROCESSING /* <- user-initiated break processing AT BREAK OF #CNTL WRITE 'SUMMARY FOR SALARY GREATER 150000' 'SUM:' SUM(SALARY(1)) 'TOTAL:' TOTAL(SALARY(1)) END-BREAK END-IF DISPLAY NAME DEPT SALARY(1) END-READ END
Page
1 NAME
04-12-14
14:13:35
DEPARTMENT ANNUAL CODE SALARY -------------------- ---------- ---------JENSEN PETERSEN MORTENSEN MADSEN BUHL ADMA01 ADMA01 ADMA01 ADMA01 ADMA01 180000 105000 320000 149000 642000 1396000 1396000 1142000
SUMMARY FOR ALL SALARIES SUM: 1396000 TOTAL: SUMMARY FOR SALARY GREATER 100000 SUM: 1396000 TOTAL: SUMMARY FOR SALARY GREATER 150000 SUM: 1142000 TOTAL: HERMANSEN ADMA02 391500 PLOUG ADMA02 162900 SUMMARY FOR ALL SALARIES SUM: 554400 TOTAL:
1950400
360
Programming Guide
Control Breaks
SUMMARY FOR SALARY GREATER 100000 SUM: SUMMARY FOR SALARY GREATER 150000 SUM: 554400 TOTAL: 554400 TOTAL: 1950400 1696400
Programming Guide
361
362
46
Data Computation
COMPUTE Statement .................................................................................................................... 364 Statements MOVE and COMPUTE ................................................................................................... 365 Statements ADD, SUBTRACT, MULTIPLY and DIVIDE ......................................................................... 366 Example of MOVE, SUBTRACT and COMPUTE Statements .................................................................. 366 COMPRESS Statement .................................................................................................................. 367 Example of COMPRESS and MOVE Statements ................................................................................. 368 Example of COMPRESS Statement .................................................................................................. 369 Mathematical Functions .................................................................................................................. 370 Further Examples of COMPUTE, MOVE and COMPRESS Statements ..................................................... 371
363
Data Computation This chapter discusses arithmetic statements that are used for computing data:
COMPUTE ADD SUBTRACT MULTIPLY DIVIDE
In addition, the following statements are discussed which are used to transfer the value of an operand into one or more fields:
MOVE COMPRESS
Important: For optimum processing, user-defined variables used in arithmetic statements should be defined with format P (packed numeric).
COMPUTE Statement
The COMPUTE statement is used to perform arithmetic operations. The following connecting operators are available:
** * / + Exponentiation Multiplication Division Addition Subtraction
Example 1:
COMPUTE LEAVE-DUE = LEAVE-DUE * 1.1
In this example, the value of the field LEAVE-DUE is multiplied by 1.1, and the result is placed in the field LEAVE-DUE.
364
Programming Guide
In this example, the square root of the value of the field #B is evaluated, and the result is assigned to the field #A.
SQRT is a mathematical function supported in the following arithmetic statements:
COMPUTE ADD SUBTRACT MULTIPLY DIVIDE
In this example, the first bonus of the current year and the current salary amount are added and assigned to the field #INCOME.
Programming Guide
365
Data Computation
ADD +5 -2 -1 GIVING #A SUBTRACT 6 FROM 11 GIVING #B MULTIPLY 3 BY 4 GIVING #C DIVIDE 3 INTO #D GIVING #E
All four statements have a ROUNDED option, which you can use if you wish the result of the operation to be rounded. For rules on rounding, see Rules for Arithmetic Assignment. The Statements documentation provides more detailed information on these statements.
** Example 'COMPUX01': COMPUTE ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 BIRTH 2 JOB-TITLE 2 SALARY (1:1) 2 BONUS (1:1,1:1) * 1 #DATE (N8) 1 REDEFINE #DATE 2 #YEAR (N4) 2 #MONTH (N2) 2 #DAY (N2) 1 #BIRTH-YEAR (A4) 1 REDEFINE #BIRTH-YEAR 2 #BIRTH-YEAR-N (N4) 1 #AGE (N3) 1 #INCOME (P9)
366
Programming Guide
Data Computation
END-DEFINE * MOVE *DATN TO #DATE * READ (3) MYVIEW BY NAME STARTING FROM 'JONES' MOVE EDITED BIRTH (EM=YYYY) TO #BIRTH-YEAR SUBTRACT #BIRTH-YEAR-N FROM #YEAR GIVING #AGE /* COMPUTE #INCOME = BONUS (1:1,1:1) + SALARY (1:1) /* DISPLAY NAME 'POSITION' JOB-TITLE #AGE #INCOME END-READ END
Page
04-11-11
14:15:54
NAME POSITION #AGE #INCOME -------------------- ------------------------- ---- ---------JONES JONES JONES MANAGER DIRECTOR PROGRAMMER 63 58 48 55000 50000 31000
COMPRESS Statement
The COMPRESS statement is used to transfer (combine) the contents of two or more operands into a single alphanumeric field. Leading zeros in a numeric field and trailing blanks in an alphanumeric field are suppressed before the field value is moved to the receiving field. By default, the transferred values are separated from one another by a single blank in the receiving field. For other separating possibilities, see the COMPRESS statement option LEAVING NO SPACE (in the Statements documentation).
Programming Guide
367
In this example, a COMPRESS statement is used to combine a text constant ('NAME:'), a database field (FIRST-NAME) and a user-defined variable (#LAST-NAME) into one user-defined variable (#FULLNAME). For further information on the COMPRESS statement, please refer to the COMPRESS statement description (in the Statements documentation).
** Example 'COMPRX01': COMPRESS ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 MIDDLE-I * 1 #LAST-NAME (A15) 1 #FULL-NAME (A30) END-DEFINE * READ (3) MYVIEW BY NAME STARTING FROM 'JONES' MOVE NAME TO #LAST-NAME /* COMPRESS 'NAME:' FIRST-NAME MIDDLE-I #LAST-NAME INTO #FULL-NAME /* DISPLAY #FULL-NAME (UC==) FIRST-NAME 'I' MIDDLE-I (AL=1) NAME END-READ END
Output of Program COMPRX01: Notice the output format of the compressed field.
368
Programming Guide
Data Computation
Page
04-11-11
14:15:54
#FULL-NAME FIRST-NAME I NAME ============================== -------------------- - -------------------NAME: VIRGINIA J JONES NAME: MARSHA JONES NAME: ROBERT B JONES VIRGINIA MARSHA ROBERT J JONES JONES B JONES
In multiple-line displays, it may be useful to combine fields/text in a user-defined variables by using a COMPRESS statement.
** Example 'COMPRX02': COMPRESS ************************************************************************ DEFINE DATA LOCAL 1 VIEWEMP VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 SALARY (1:1) 2 CURR-CODE (1:1) 2 CITY 2 ADDRESS-LINE (1:1) 2 ZIP * 1 #FULL-SALARY (A25) 1 #FULL-NAME (A25) 1 #FULL-CITY (A25) END-DEFINE * READ (3) VIEWEMP BY CITY STARTING FROM 'NEW YORK' COMPRESS 'SALARY:' CURR-CODE(1) SALARY(1) INTO #FULL-SALARY COMPRESS FIRST-NAME NAME INTO #FULL-NAME COMPRESS ZIP CITY INTO #FULL-CITY /* DISPLAY 'NAME AND ADDRESS' NAME (EM=X^X^X^X^X^X^X^X^X^X^X^X) WRITE 1/5 #FULL-NAME 1/37 #FULL-SALARY 2/5 ADDRESS-LINE (1) 3/5 #FULL-CITY SKIP 1
Programming Guide
369
Data Computation
END-READ END
Page
04-11-11
14:15:54
NAME AND ADDRESS ----------------------R U B I N SYLVIA RUBIN 2003 SARAZEN PLACE 10036 NEW YORK W A L L A C E MARY WALLACE 12248 LAUREL GLADE C 10036 NEW YORK K E L L O G G HENRIETTA KELLOGG 1001 JEFF RYAN DR. 19711 NEWARK
Mathematical Functions
The following Natural mathematical functions are supported in arithmetic processing statements (ADD, COMPUTE, DIVIDE, SUBTRACT, MULTIPLY).
Mathematical Function Absolute value of field. Arc tangent of field. Cosine of field. Exponential of field. Fractional part of field. Integer part of field. Natural logarithm of field. Sign of field. Sine of field. Square root of field. Tangent of field. Natural System Function ABS(field) ATN(field) COS(field) EXP(field) FRAC(field) INT(field) LOG(field) SGN(field) SIN(field) SQRT(field) TAN(field)
370
Programming Guide
Data Computation
Mathematical Function Natural System Function
See also the System Functions documentation for a detailed explanation of each mathematical function.
WRITEX11 - WRITE (with nX, n/n and COMPRESS) IFX03 - IF statement COMPRX03 - COMPRESS (using parameters LC and TC)
Programming Guide
371
372
47
System Variables ........................................................................................................................... 374 System Functions .......................................................................................................................... 376 Example of System Variables and System Functions ............................................................................ 376 Further Examples of System Variables ............................................................................................... 378 Further Examples of System Functions .............................................................................................. 378
373
System Variables and System Functions This chapter describes the purpose of Natural system variables and Natural system functions and how they are used in Natural programs.
System Variables
The following topics are covered below:
Purpose
System variables are used to display system information. They may be referenced at any point within a Natural program. Natural system variables provide variable information, for example, about the current Natural session:
the current library; the user and terminal identification; the current status of a loop processing; the current report processing status; the current date and time.
The typical use of system variables is illustrated in the Example of System Variables and System Functions below and in the examples contained in library SYSEXPG. The information contained in a system variable may be used in Natural programs by specifying the appropriate system variables. For example, date and time system variables may be specified in a DISPLAY, WRITE, PRINT, MOVE or COMPUTE statement.
374
Programming Guide
System Variables and System Functions Format/Length Information on format and length is given in the detailed descriptions in the System Variables documentation. The following abbreviations are used:
Format A B D I L P T Alphanumeric Binary Date Integer Logical Packed numeric Time
N Numeric (unpacked)
Content Modifiable In the individual descriptions, this indicates whether in a Natural program you can assign another value to the system variable, that is, overwrite its content as generated by Natural.
Application Related System Variables Date and Time System Variables Input/Ouput Related System Variables Natural Environment Related System Variables System Environment Related System Variables XML Related System Variables
For detailed descriptions of all system variables, see the System Variables documentation.
Programming Guide
375
System Functions
Natural system functions comprise a set of statistical and mathematical functions that can be applied to the data after a record has been processed, but before break processing occurs. System functions may be specified in a DISPLAY, WRITE, PRINT, MOVE or COMPUTE statement that is used in conjunction with an AT END OF PAGE, AT END OF DATA or AT BREAK statement. In the case of an AT END OF PAGE statement, the corresponding DISPLAY statement must include the GIVE SYSTEM FUNCTIONS clause (as shown in the example below). The following functional groups of system functions exist:
System Functions for Use in Processing Loops Mathematical Functions Miscellaneous Functions
For detailed information on all system functions available, see the System Functions documentation. See also Using System Functions in Processing Loops (in the System Functions documentation). The typical use of system functions is explained in the example programs given below and in the examples contained in library SYSEXPG.
** Example 'SYSVAX01': System variables and system functions ************************************************************************ DEFINE DATA LOCAL 1 MYVIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 JOB-TITLE 2 INCOME (1:1) 3 CURR-CODE 3 SALARY 3 BONUS (1:1) END-DEFINE * WRITE TITLE LEFT JUSTIFIED 'EMPLOYEE SALARY REPORT AS OF' *DAT4E / *
376
Programming Guide
Explanation:
The system variable *DATE is output with the WRITE TITLE statement. The system variable *TIME is output with the AT START OF DATA statement. The system function OLD is used in the AT END OF DATA statement. The system function AVER is used in the AT END OF PAGE statement.
Output of Program SYSVAX01: Note how the system variables and system function are displayed.
CURRENCY ANNUAL BONUS CODE SALARY --------------- --------------- -------- ---------- ---------REPORT CREATED AT: 14:15:55.0 HOURS DUYVERMAN PRATT MARKUSH PROGRAMMER SALES PERSON TRAINEE USD USD USD 34000 38000 22000 0 9000 0
Programming Guide
377
EDITMX05 - Edit mask (EM for date and time system variables) READX04 - READ (in combination with FIND and the system variables *NUMBER and *COUNTER) WTITLX01 - WRITE TITLE (with *PAGE-NUMBER)
ATBREX06 - AT BREAK OF (comparing NMIN, NAVER, NCOUNT with MIN, AVER, COUNT) ATENPX01 - AT END OF PAGE (with system function available via GIVE SYSTEM FUNCTIONS in DISPLAY)
378
Programming Guide
48
Stack
Use of Natural Stack ...................................................................................................................... 380 Stack Processing ........................................................................................................................... 380 Placing Data on the Stack ............................................................................................................... 381 Deleting the First Entry from the Stack ............................................................................................... 382 Clearing the Stack ......................................................................................................................... 382
379
Stack The Natural stack is a kind of intermediate storage in which you can store Natural commands, user-defined commands, and input data to be used by an INPUT statement.
Stack Processing
The processing of the commands/data stored in the stack differs depending on the function being performed. If a command is expected, that is, the NEXT prompt is about to be displayed, Natural first checks if a command is on the top of the stack. If there is, the NEXT prompt is suppressed and the command is read and deleted from the stack; the command is then executed as if it had been entered manually in response to the NEXT prompt. If an INPUT statement containing input fields is being executed, Natural first checks if there are any input data on the top of the stack. If there are, these data are passed to the INPUT statement (in delimiter mode); the data read from the stack must be format-compatible with the variables in the INPUT statement; the data are then deleted from the stack. See also Processing Data from the Natural Stack in the INPUT statement description. If an INPUT statement was executed using data from the stack, and this INPUT statement is re-executed via a REINPUT statement, the INPUT statement screen will be re-executed displaying the same data from the stack as when it was executed originally. With the REINPUT statement, no further data are read from the stack. When a Natural program terminates normally, the stack is flushed beginning from the top until either a command is on the top of the stack or the stack is cleared. When a Natural program is terminated via the terminal command %% or with an error, the stack is cleared entirely.
380
Programming Guide
Stack
STACK Parameter
The Natural profile parameter STACK may be used to place data/commands on the stack. The STACK parameter (described in the Parameter Reference) can be specified by the Natural administrator in the Natural parameter module at the installation of Natural; or you can specify it as a dynamic parameter when you invoke Natural. When data/commands are to be placed on the stack via the STACK parameter, multiple commands must be separated from one another by a semicolon (;). If a command is to be passed within a sequence of data or command elements, it must be preceded by a semicolon. Data for multiple INPUT statements must be separated from one another by a colon (:). Data that are to be read by a separate INPUT statement must be preceded by a colon. If a command is to be stacked which requires parameters, no colon is to be placed between the command and the parameters. Semicolon and colon must not be used within the input data themselves as they will be interpreted as separation characters.
STACK Statement
The STACK statement can be used within a program to place data/commands in the stack. The data elements specified in one STACK statement will be used for one INPUT statement, which means that if data for multiple INPUT statements are to be placed on the stack, multiple STACK statements must be used. Data may be placed on the stack either unformatted or formatted:
If unformatted data are read from the stack, the data string is interpreted in delimiter mode and the characters specified with the session parameters IA (Input Assignment character) and ID (Input Delimiter character) are processed as control characters for keyword assignment and data separation. If formatted data are placed on the stack, each content of a field will be separated and passed to one input field in the corresponding INPUT statement. If the data to be placed on the stack contains delimiter, control or DBCS characters, it should be placed formatted on the stack to avoid unintentional interpretation of these characters.
Programming Guide
381
Stack See the Statements documentation for further information on the STACK statement.
382
Programming Guide
49
Edit Masks for Date Fields and Date System Variables .......................................................................... 384 Default Edit Mask for Date - DTFORM Parameter ................................................................................ 384 Date Format for Alphanumeric Representation - DF Parameter ............................................................... 385 Date Format for Output - DFOUT Parameter ....................................................................................... 388 Date Format for Stack - DFSTACK Parameter ..................................................................................... 389 Year Sliding Window - YSLW Parameter ............................................................................................. 390 Combinations of DFSTACK and YSLW ............................................................................................... 392 Year Fixed Window ........................................................................................................................ 395 Date Format for Default Page Title - DFTITLE Parameter ...................................................................... 395
383
Processing of Date Information This chapter covers various aspects concerning the handling of date information in Natural applications.
Example
yyyy-mm-dd 2005-12-31
The DTFORM parameter can be set in the Natural parameter module/file or dynamically when Natural is invoked. By default, DTFORM=I applies.
384
Programming Guide
For each representation, the sequence of the day, month and year components, and the delimiter characters used, are determined by the DTFORM parameter. By default, DF=S applies (except for INPUT statements; see below). The session parameter DF is evaluated at compilation. It can be specified with the following statements:
FORMAT, INPUT, DISPLAY, WRITE
and PRINT at statement and element (field) level, and FETCH at element (field) level.
When specified in one of these statements, the DF parameter applies to the following:
Statement DISPLAY, WRITE, PRINT Effect of DF parameter When the value of a date variable is output with one of these statements, the value is converted to an alphanumeric representation before it is output. The DF parameter determines which representation is used.
MOVE, COMPRESS When the value of a date variable is transferred to an alphanumeric field with a MOVE or COMPRESS statement, the value is converted to an alphanumeric representation before it is transferred. The DF parameter determines which representation is used. STACK, RUN, FETCH When the value of a date variable is placed on the stack, it is converted to alphanumeric representation before it is placed on the stack. The DF parameter determines which representation is used. The same applies when a date variable is specified as a parameter in a FETCH or RUN statement (as these parameters are also passed via the stack).
Programming Guide
385
Note: With DF=S, only 2 digits are provided for the year information; this means that if a date value contained the century, this information would be lost during the conversion. To retain the century information, you set DF=I or DF=L.
/* DF=S (default) WRITE *DATX /* Output has this format: dd.mm.yy END
DEFINE DATA LOCAL 1 #DATE (D) INIT <D'31/12/2005'> 1 #ALPHA (A10) END-DEFINE ... MOVE #DATE TO #ALPHA /* Result: #ALPHA contains 31/12/05 MOVE #DATE (DF=I) TO #ALPHA /* Result: #ALPHA contains 31122005 MOVE #DATE (DF=L) TO #ALPHA /* Result: #ALPHA contains 31/12/2005 ...
386
Programming Guide
DEFINE DATA LOCAL 1 #DATE (D) INIT <D'2005-12-31'> 1 #ALPHA1(A10) 1 #ALPHA2(A10) 1 #ALPHA3(A10) END-DEFINE ... STACK TOP DATA #DATE (DF=S) #DATE (DF=I) #DATE (DF=L) ... INPUT #ALPHA1 #ALPHA2 #ALPHA3 ... /* Result: #ALPHA1 contains 05-12-31 /* #ALPHA2 contains 20051231 /* #ALPHA3 contains 2005-12-31 ...
DEFINE DATA LOCAL 1 #DATE1 (D) 1 #DATE2 (D) 1 #DATE3 (D) 1 #DATE4 (D) END-DEFINE ... INPUT #DATE1 (DF=S) #DATE2 (DF=I) #DATE3 (DF=L) #DATE4 ...
/* /* /* /*
Programming Guide
387
By default, DFOUT=S applies. For either DFOUT setting, the sequence of the day, month and year components in the date values is determined by the DTFORM parameter. The lengths of the date fields are not affected by the DFOUT setting, as either date value representation fits into an 8-byte field. The DFOUT parameter can be set in the Natural parameter module/file, dynamically when Natural is invoked, or with the system command GLOBALS. It is evaluated at runtime. Example: This example assumes that DTFORM=I applies.
DEFINE DATA LOCAL 1 #DATE (D) INIT <D'2005-12-31'> END-DEFINE ... WRITE #DATE /* Output if DFOUT=S is set ...: 05-12-31 /* Output if DFOUT=I is set ...: 20051231 WRITE #DATE (DF=L) /* Output (regardless of DFOUT): 2005-12-31 ...
388
Programming Guide
By default, DFSTACK=S applies. DFSTACK=S means that when a date value is placed on the stack, it is placed there without the century information (which is lost). When the value is then read from the stack and placed into another date variable, the century is either assumed to be the current one or determined by the setting of the YSLW parameter (see below). This might lead to the century being different from that of the original date value; however, Natural would not issue any error in this case.
DFSTACK=C works the same as DFSTACK=S in that a date value is placed on the stack without the
century information. However, if the value is read from the stack and the resulting century is different from that of the original date value (either because of the YSLW parameter, or the original century not being the current one), Natural issues a runtime error. Note: This runtime error is already issued at the time when the value is placed on the stack.
DFSTACK=I allows you to place a date value on the stack in a length of 8 bytes without losing the
century information. The DFSTACK parameter can be set in the Natural parameter module/file, dynamically when Natural is invoked, or with the system command GLOBALS. It is evaluated at runtime.
Programming Guide
389
Processing of Date Information Example: This example assumes that DTFORM=I and YSLW=0 apply.
DEFINE DATA LOCAL 1 #DATE (D) INIT <D'2005-12-31'> 1 #ALPHA1(A8) 1 #ALPHA2(A10) END-DEFINE ... STACK TOP DATA #DATE #DATE (DF=L) ... INPUT #ALPHA1 #ALPHA2 ... /* Result if DFSTACK=S or =C is set: #ALPHA1 contains 05-12-31 /* Result if DFSTACK=I is set .....: #ALPHA1 contains 20051231 /* Result (regardless of DFSTACK) .: #ALPHA2 contains 2005-12-31 ...
used with the mathematical function VAL(field), used with the IS(D) option in a logical condition, read from the stack as input data, or entered in an input field as input data.
The YSLW parameter determines the range of years covered by a so-called year sliding window. The sliding-window mechanism assumes a date with a 2-digit year to be within a window of 100 years. Within these 100 years, every 2-digit year value can be uniquely related to a specific century. With the YSLW parameter, you determine how many years in the past that 100-year range is to begin: The YSLW value is subtracted from the current year to determine the first year of the window range. Possible values of the YSLW parameter are 0 to 99. The default value is YSLW=0, which means that no sliding-window mechanism is used; that is, a date with a 2-digit year is assumed to be in the current century.
390
Programming Guide
Processing of Date Information Example 1: If the current year is 2005 and you specify YSLW=40, the sliding window will cover the years 1965 to 2064. A 2-digit year value nn from 65 to 99 is interpreted accordingly as 19nn, while a 2-digit year value nn from 00 to 64 is interpreted as 20nn.
Example 2: If the current year is 2005 and you specify YSLW=20, the sliding window will cover the years 1985 to 2084. A 2-digit year value nn from 85 to 99 is interpreted accordingly as 19nn, while a 2-digit year value nn from 00 to 84 is interpreted as 20nn.
Programming Guide
391
392
Programming Guide
Processing of Date Information Example 1: This example assumes the current year to be 2005, and that the parameter settings DFSTACK=S (default) and YSLW=20 apply.
DEFINE DATA LOCAL 1 #DATE1 (D) INIT <D'1956-12-31'> 1 #DATE2 (D) END-DEFINE ... STACK TOP DATA #DATE1 /* century information is lost (year 56 is stacked) ... INPUT #DATE2 /* year sliding window determines 56 to be 2056 ... /* Result: #DATE2 contains 2056-12-31 even if #DATE1 is set to <D'2156-12-31'>
In this case, the year sliding window is not set appropriately, so that the century information is (inadvertently) changed. Example 2: This example assumes the current year to be 2005, and that the parameter settings DFSTACK=S (default) and YSLW=60 apply.
DEFINE DATA LOCAL 1 #DATE1 (D) INIT <D'1956-12-31'> 1 #DATE2 (D) END-DEFINE ... STACK TOP DATA #DATE1 /* century information is lost (year 56 is stacked) ... INPUT #DATE2 /* year sliding window determines 56 to be 1956 ... /* Result: #DATE2 contains 1956-12-31 even if #DATE1 is set to <D'2056-12-31'>
In this case, the year sliding window is set appropriately, so that the original century information is correctly restored.
Programming Guide
393
Processing of Date Information Example 3: This example assumes the current year to be 2005, and that the parameter settings DFSTACK=C and YSLW=0 (default) apply.
DEFINE DATA LOCAL 1 #DATE1 (D) INIT <D'1956-12-31'> 1 #DATE2 (D) END-DEFINE ... STACK TOP DATA #DATE1 /* century information is lost (year 56 is stacked) ... INPUT #DATE2 /* 56 is assumed to be in current century -> 1956 ... /* Result: RUNTIME ERROR (UNINTENDED CENTURY CHANGE)
In this case, the century information is (inadvertently) changed. However, this change is intercepted by the DFSTACK=C setting. Example 4: This example assumes the current year to be 2005, and that the parameter settings DFSTACK=C and YSLW=60 (default) apply.
DEFINE DATA LOCAL 1 #DATE1 (D) INIT <D'2056-12-31'> 1 #DATE2 (D) END-DEFINE ... STACK TOP DATA #DATE1 /* century information is lost (year 56 is stacked) ... INPUT #DATE2 /* year sliding window determines 56 to be 1956 ... /* Result: RUNTIME ERROR (UNINTENDED CENTURY CHANGE)
In this case, the century information is changed due to the year sliding window. However, this change is intercepted by the DFSTACK=C setting.
394
Programming Guide
For each of these output formats, the sequence of the day, month and year components, and the delimiter characters used, are determined by the DTFORM parameter. The DFTITLE parameter can be set in the Natural parameter module/file, dynamically when Natural is invoked, or with the system command GLOBALS. It is evaluated at runtime. Example: This example assumes that DTFORM=I applies.
WRITE 'HELLO' END /* /* Date in page title if DFTITLE=S is set ...: 05-10-31 /* Date in page title if DFTITLE=L is set ...: 2005-10-31 /* Date in page title if DFTITLE=I is set ...: 20051031
Note: The DFTITLE parameter has no effect on a user-defined page title as specified with a
WRITE TITLE statement.
Programming Guide
395
396
50
Text Notation
Defining a Text to Be Used with a Statement - the 'text' Notation ............................................................. 398 Defining a Character to Be Displayed n Times before a Field Value - the 'c'(n) Notation ............................... 400
397
Text Notation In an INPUT, DISPLAY, WRITE, WRITE TITLE or WRITE TRAILER statement, you can use text notation to define a text to be used in conjunction with such a statement.
DEFINE DATA LOCAL 1 #A(A10) END-DEFINE INPUT 'Input XYZ' (CD=BL) #A WRITE '=' #A WRITE 'Write1 ' - 'Write2 ' - 'Write3' (CD=RE) END
398
Programming Guide
O'CONNOR
O"CONNOR
Programming Guide
399
Text Notation
Defining a Character to Be Displayed n Times before a Field Value - the 'c'(n) Notation
If a single character is to be output several times as text, you use the following notation:
'c'(n)
As c you specify the character, and as n the number of times the character is to be generated. The maximum value for n is 249. Example:
WRITE '*'(3)
Instead of apostrophes before and after the character c you can also use quotation marks.
400
Programming Guide
51
User Comments
Using an Entire Source Code Line for Comments ................................................................................. 402 Using the Latter Part of a Source Code Line for Comments .................................................................... 403
401
User Comments User comments are descriptions or explanatory notes added to or interspersed among the statements of the source code. Such information may be particularly helpful in understanding and maintenaing source code that was written or edited by another programmer. Also, the characters marking the beginning of a comment can be used to temporarily disable the function of a statement or several source code lines for test purposes.
an asterisk and a blank (* ), two asterisks (**), or a slash and an asterisk (/*).
Example: As can be seen from the following example, comment lines may also be used to provide for a clear source code structure.
** Example 'LOGICX03': BREAK option in logical condition ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 BIRTH * 1 #BIRTH (A8) END-DEFINE * LIMIT 10 READ EMPLOY-VIEW BY BIRTH MOVE EDITED BIRTH (EM=YYYYMMDD) TO #BIRTH /* IF BREAK OF #BIRTH /6/ NEWPAGE IF LESS THAN 5 LINES LEFT WRITE / '-' (50) / END-IF /*
402
Programming Guide
User Comments
DISPLAY NOTITLE BIRTH (EM=YYYY-MM-DD) NAME FIRST-NAME END-READ END
ADD 5 TO #A
/* USER COMMENT
Example:
** Example 'LOGICX04': IS option as format/length check ************************************************************************ DEFINE DATA LOCAL 1 #FIELDA (A10) /* INPUT FIELD TO BE CHECKED 1 #FIELDB (N5) /* RECEIVING FIELD OF VAL FUNCTION 1 #DATE (A10) /* INPUT FIELD FOR DATE END-DEFINE * INPUT #DATE #FIELDA IF #DATE IS(D) IF #FIELDA IS (N5) COMPUTE #FIELDB = VAL(#FIELDA) WRITE NOTITLE 'VAL FUNCTION OK' // '=' #FIELDA '=' #FIELDB ELSE REINPUT 'FIELD DOES NOT FIT INTO N5 FORMAT' MARK *#FIELDA END-IF ELSE REINPUT 'INPUT IS NOT IN DATE FORMAT (YY-MM-DD) ' MARK *#DATE END-IF * END
Programming Guide
403
404
52
Introduction .................................................................................................................................. 406 Relational Expression ..................................................................................................................... 407 Extended Relational Expression ....................................................................................................... 411 Evaluation of a Logical Variable ........................................................................................................ 412 Fields Used within Logical Condition Criteria ....................................................................................... 413 Logical Operators in Complex Logical Expressions ............................................................................... 415 BREAK Option - Compare Current Value with Value of Previous Loop Pass .............................................. 417 IS Option - Check whether Content of Alphanumeric or Unicode Field can be Converted ............................. 419 MASK Option - Check Selected Positions of a Field for Specific Content ................................................... 421 MASK Option Compared with IS Option ............................................................................................. 428 MODIFIED Option - Check whether Field Content has been Modified ....................................................... 430 SCAN Option - Scan for a Value within a Field ..................................................................................... 432 SPECIFIED Option - Check whether a Value is Passed for an Optional Parameter ...................................... 434
405
Logical Condition Criteria This chapter describes purpose and use of logical condition criteria that can be used in the statements FIND, READ, HISTOGRAM, ACCEPT/REJECT, IF, DECIDE FOR, REPEAT.
Introduction
The basic criterion is a relational expression. Multiple relational expressions may be combined with logical operators (AND, OR) to form complex criteria. Arithmetic expressions may also be used to form a relational expression. Logical condition criteria can be used in the following statements:
Statement
FIND
Usage A WHERE clause containing logical condition criteria may be used to indicate criteria in addition to the basic selection criteria as specified in the WITH clause. The logical condition criteria specified with the WHERE clause are evaluated after the record has been selected and read. In a WITH clause, basic search criteria (as described with the FIND statement) are used, but not logical condition criteria.
READ
A WHERE clause containing logical condition criteria may be used to specify whether a record that has just been read is to be processed. The logical condition criteria are evaluated after the record has been read. A WHERE clause containing logical condition criteria may be used to specify whether the value that has just been read is to be processed. The logical condition criteria are evaluated after the value has been read. condition criteria in addition to that specified when the record was selected/read with a FIND, READ, or HISTOGRAM statement. The logical condition criteria are evaluated after the record has been read and after record processing has started.
HISTOGRAM
ACCEPT/REJECT An IF clause may be used with an ACCEPT or REJECT statement to specify logical
Logical condition criteria are used to control statement execution. Logical condition criteria are used to control statement execution. The UNTIL or WHILE clause of a REPEAT statement contain logical condition criteria which determine when a processing loop is to be terminated.
406
Programming Guide
Relational Expression
Syntax:
EQ = EQUAL EQUAL TO NE = <> NOT = NOT EQ NOTEQUAL NOT EQUAL NOT EQUAL TO LT LESS THAN < GE GREATER EQUAL >= NOT < NOT LT GT GREATER THAN > LE LESS EQUAL <= NOT > NOT GT
operand1
operand2
operand1 C S A operand2 C S A
N E A U N P I F B D T L N E A U N P I F B D T L
For an explanation of the Operand Definition Table shown above, see Syntax Symbols and Operand Definition Tables in the Statements documentation.
Programming Guide
407
Logical Condition Criteria In the Possible Structure column of the table above, E stands for arithmetic expressions; that is, any arithmetic expression may be specified as an operand within the relational expression. For further information on arithmetic expressions, see arithmetic-expression in the COMPUTE statement description. Explanation of the comparison operators:
Comparison Operator Explanation
EQ = EQUAL EQUAL TO NE = <> NOT = NOT EQ NOTEQUAL NOT EQUAL NOT EQUAL TO LT LESS THAN < GE GREATER EQUAL >= NOT < NOT LT GT GREATER THAN > LE LESS EQUAL <= NOT > NOT GT
equal to
not equal to
less than
408
Programming Guide
For information on comparing arrays in a relational expression, see Processing of Arrays. Note: If a floating-point operand is used, comparison is performed in floating point. Floating-point numbers as such have only a limited precision; therefore, rounding/truncation errors cannot be precluded when numbers are converted to/from floating-point representation. Arithmetic Expressions in Logical Conditions The following example shows how arithmetic expressions can be used in logical conditions:
IF #A + 3 GT #B - 5 AND #C * 3 LE #A + #B
Handles in Logical Conditions If the operands in a relation expression are handles, only EQUAL and NOT EQUAL operators may be used. SUBSTRING Option in Relational Expression Syntax:
= EQ EQUAL [TO] = <> NE NOT = NOT EQ NOT EQUAL NOT EQUAL TO < LT LESS THAN <= LE LESS EQUAL > GT GREATER THAN
Programming Guide
409
With the SUBSTRING option, you can compare a part of an alphanumeric, a binary or a Unicode field. After the field name (operand1) you specify first the starting position (operand3) and then the length (operand4) of the field portion to be compared. Also, you can compare a field value with part of another field value. After the field name (operand2) you specify first the starting position (operand5) and then the length (operand6) of the field portion operand1 is to be compared with. You can also combine both forms, that is, you can specify a SUBSTRING for both operand1 and operand2. Examples: The following expression compares the 5th to 12th position inclusive of the value in field #A with the value of field #B:
SUBSTRING(#A,5,8) = #B
410
Programming Guide
Logical Condition Criteria The following expression compares the value of field #A with the 3rd to 6th position inclusive of the value in field #B:
#A = SUBSTRING(#B,3,4)
Note: If you omit operand3/operand5, the starting position is assumed to be 1. If you omit
operand4/operand6, the length is assumed to be from the starting position to the end of the
field.
operand1
operand3
N* E A U N P I F B D T N* E A U N P I F B D T N* E A U N P I F B D T N* E A U N P I F B D T N* E A U N P I F B D T N* E A U N P I F B D T
Mathematical functions and system variables are permitted. Break functions are not permitted.
Programming Guide
411
For details on these options, see the sections MASK Option and SCAN Option. Examples:
IF #A = 2 OR = 4 OR = 7 IF #A = 5 THRU 11 BUT NOT 7 THRU 8
This option is used in conjunction with a logical variable (format L). A logical variable may take the value TRUE or FALSE. As operand1 you specify the name of the logical variable to be used. Operand Definition Table:
Operand Possible Structure Possible Formats L Referencing Permitted Dynamic Definition no no
operand1 C S A
412
Programming Guide
Programming Guide
413
Logical Condition Criteria The following table shows which operand formats can be used together in a logical condition:
operand1 operand2
D T I F L N P GH OH
Y Y Y Y Y [2] Y Y Y Y Y Y Y Y Y Y Y Y
Y Y Y Y
Y Y
Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y
Y Y Y Y Y Y Y Y Y Y Y Y Y Y
Notes: 1. [1] where GH = GUI handle, OH = object handle. 2. [2] The binary value will be assumed to contain Unicode code points, and the comparison is performed as for a comparison of two Unicode values. The length of the binary field must be even. If two values are compared as alphanumeric values, the shorter value is assumed to be extended with trailing blanks in order to get the same length as the longer value. If two values are compared as binary values, the shorter value is assumed to be extended with leading binary zeroes in order to get the same length as the longer value. If two values are compared as Unicode values, trailing blanks are removed from both values before the ICU collation algorithm is used to compare the two resulting values. See also Logical Condition Criteria in the Unicode and Code Page Support documentation.
414
Programming Guide
If an array is compared with a scalar value, each element of the array will be compared with the scalar value. The condition will be true if at least one of the array elements meets the condition (OR operation). If an array is compared with an array, each element in the array is compared with the corresponding element of the other array. The result is true only if all element comparisons meet the condition (AND operation). See also Processing of Arrays. Note: An Adabas phonetic descriptor cannot be used within a logical condition. Examples of Logical Condition Criteria:
FIND EMPLOYEES-VIEW WITH CITY = 'BOSTON' WHERE SEX = 'M' READ EMPLOYEES-VIEW BY NAME WHERE SEX = 'M' ACCEPT IF LEAVE-DUE GT 45 IF #A GT #B THEN COMPUTE #C = #A + #B REPEAT UNTIL #X = 500
Programming Guide
415
Logical Condition Criteria The operators are evaluated in the following order:
Priority Operator Meaning 1 2 3 4
( ) NOT AND OR
Parentheses Negation
AND operation OR operation
The following logical-condition-criteria may be combined by logical operators to form a complex logical-expression:
MASK SCAN
BREAK
[NOT]
logical-expression
For information on comparing arrays in a logical expression, see Processing of Arrays. Note: If multiple logical-condition-criteria are connected with AND, the evaluation terminates as soon as the first of these criteria is not true.
416
Programming Guide
BREAK Option - Compare Current Value with Value of Previous Loop Pass
The BREAK option allows the current value or a portion of a value of a field to be compared with the value contained in the same field in the previous pass through the processing loop. Syntax:
BREAK [OF] operand1 [/n/]
Possible Structure S
Possible Formats A U N P I F B D T L
The notation /n/ may be used to indicate that only the first n positions (counting from left to right) of the control field are to be checked for a change in value. This notation can only be used with operands of format A, B, N, or P. The result of the BREAK operation is true when a change in the specified positions of the field occurs. The result of the BREAK operation is not true if an AT END OF DATA condition occurs. Example: In this example, a check is made for a different value in the first position of the field FIRST-NAME.
BREAK FIRST-NAME /1/
Natural system functions (which are available with the AT BREAK statement) are not available with this option.
Programming Guide
417
-------------------------------------------------1940-02-02 1940-02-13 1940-02-14 1940-02-24 WINTRICH KUNEY KOLENCE DILWORTH MARIA MARY MARSHA TOM
418
Programming Guide
This option is used to check whether the content of an alphanumeric or Unicode field (operand1) can be converted to a specific other format. Operand Definition Table:
Operand Possible Structure N Possible Formats A U Referencing Permitted Dynamic Definition yes no
operand1 C S A
T Pll.ll Ill
When the check is performed, leading and trailing blanks in operand1 will be ignored. The IS option may, for example, be used to check the content of a field before the mathematical function VAL (extract numeric value from an alphanumeric field) is used to ensure that it will not result in a runtime error. Note: The IS option cannot be used to check if the value of an alphanumeric field is in the specified format, but if it can be converted to that format. To check if a value is in a specific format, you can use the MASK option. For further information, see MASK Option Compared with IS Option and Checking Packed or Unpacked Numeric Data.
Programming Guide
419
420
Programming Guide
Constant Mask Variable Mask Characters in a Mask Mask Length Checking Dates Checking Against the Content of Constants or Variables Range Checks Checking Packed or Unpacked Numeric Data
Constant Mask
Syntax:
= EQ EQUAL TO NE NOT EQUAL
operand1
operand1 C S A operand2 C S
operand2 can only be used if the mask-definition contains at least one X. operand1 and operand2
must be format-compatible:
If operand1 is of format A, operand2 must be of format A, B, N or U. If operand1 is of format U, operand2 must be of format A, B, N or U. If operand1 is of format N or P, operand2 must be of format N or P.
An X in the mask-definition selects the corresponding positions of the content of operand1 and operand2 for comparison.
Programming Guide
421
Variable Mask
Apart from a constant mask-definition (see above), you may also specify a variable mask definition. Syntax:
= EQ EQUAL TO NE NOT EQUAL
operand1
MASK operand2
operand1 C S A operand2
The content of operand2 will be taken as the mask definition. Trailing blanks in operand2 will be ignored.
If operand1 is of format A, N or P, operand2 must be of format A. If operand1 is of format U, operand2 must be of format U.
Characters in a Mask
The following characters may be used within a mask definition (the mask definition is contained in mask-definition for a constant mask and operand2 for a variable mask):
Character
. or ? or _ * or %
Meaning A period, question mark or underscore indicates a single position that is not to be checked. An asterisk or percent mark is used to indicate any number of positions not to be checked.
422
Programming Guide
Meaning A slash (/) is used to check if a value ends with a specific character (or string of characters). For example, the following condition will be true if there is either an E in the last position of the field, or the last E in the field is followed by nothing but blanks:
IF #FIELD = MASK (*'E'/)
A 'c'
The position is to be checked for an alphabetical character (upper or lower case). One or more positions are to be checked for the characters bounded by apostrophes (a double apostrophe indicates that a single apostrophe is the character to be checked for). Alphanumeric characters with hexadecimal numbers lower than H'40' (blank) are not allowed. The position is to be checked for an alphabetical character (upper or lower case), a numeric character, or a blank. The two positions are to be checked for a valid day notation (01 - 31; dependent on the values of MM and YY/YYYY, if specified; see also Checking Dates). The position is to be checked for hexadecimal content (A - F, 0 - 9). The positions are to be checked for a valid Julian Day; that is, the day number in the year (001-366, dependent on the value of YY/YYYY, if specified. See also Checking Dates.) The position is to be checked for a lower-case alphabetical character (a - z). The positions are to be checked for a valid month (01 - 12); see also Checking Dates. The position is to be checked for a numeric digit. One (or more) positions are to be checked for a numeric value in the range 0 - n.
C DD H JJJ L MM N n...
n1-n2 or n1:n2 The positions are checked for a numeric value in the range n1-n2. n1 and n2 must be of the same length. P S U X
The position is to be checked for a displayable character (U, L, N or S). The position is to be checked for special characters. The position is to be checked for an upper-case alphabetical character (A - Z). The position is to be checked against the equivalent position in the value (operand2) following the mask-definition.
X is not allowed in a variable mask definition, as it makes no sense.
YY YYYY
The two positions are to be checked for a valid year (00 - 99). See also Checking Dates. The four positions are checked for a valid year (0000 - 2699). Use the COMPOPT option MASKCME=ON to restrict the range of valid years to 1582 - 2699; see also Checking Dates. If the profile parameter MAXYEAR is set to 9999, the upper year limit is 9999. The position is to be checked for a character whose left half-byte is hexadecimally A - F, and whose right half-byte is hexadecimally 0 - 9. This may be used to correctly check for numeric digits in negative numbers. With N (which indicates a position to be checked for a numeric digit), a check for numeric digits in negative
Programming Guide
423
Mask Length
The length of the mask determines how many positions are to be checked. Example:
DEFINE DATA LOCAL 1 #CODE (A15) END-DEFINE ... IF #CODE = MASK (NN'ABC'....NN) ...
In the above example, the first two positions of #CODE are to be checked for numeric content. The three following positions are checked for the contents ABC. The next four positions are not to be checked. Positions ten and eleven are to be checked for numeric content. Positions twelve to fifteen are not to be checked.
Checking Dates
Only one date may be checked within a given mask. When the same date component (JJJ, DD, MM, YY or YYYY) is specified more than once in the mask, only the value of the last occurrence is checked for consistency with other date components. When dates are checked for a day (DD) and no month (MM) is specified in the mask, the current month will be assumed. When dates are checked for a day (DD) or a Julian day (JJJ) and no year (YY or YYYY) is specified in the mask, the current year will be assumed. When dates are checked for a 2-digit year (YY), the current century will be assumed if no Sliding or Fixed Window is set. For more details about Sliding or Fixed Windows, refer to profile parameter YSLW in the Parameter Reference.
424
Programming Guide
In this example, month and day are checked for validity. The value for month (11) will be considered valid, whereas the value for day (31) will be invalid since the 11th month has only 30 days. Example 2:
IF #DATE(A8) = MASK (MM'/'DD'/'YY)
In this example, the content of the field #DATE is be checked for a valid date with the format MM/DD/YY (month/day/year). Example 3:
IF #DATE (A8) = MASK (1950-2020MMDD)
In this example, the content of field #DATE is checked for a four-digit number in the range 1950 to 2020 followed by a valid month and day in the current year. Note: Although apparent, the above mask does not allow to check for a valid date in the years 1950 through 2020, because the numeric value range 1950-2020 is checked independent of the validation of month and day. The check will deliver the intended results except for February, 29, where the result depends on whether the current year is a leap year or not. To check for a specific year range in addition to the date validation, code one check for the date validation and another for the range validation:
IF #DATE (A8) = MASK (YYYYMMDD) AND #DATE = MASK (1950-2020)
Example 4:
IF #DATE (A4) = MASK (19-20YY)
In this example, the content of field #DATE is checked for a two-digit number in the range 19 to 20 followed by a valid two-digit year (00 through 99). The century is supplied by Natural as described above. Note: Although apparent, the above mask does not allow to check for a valid year in the range 1900 through 2099, because the numeric value range 19-20 is checked independent of the year validation. To check for year ranges, code one check for the date validation and another for the range validation:
Programming Guide
425
In the mask, you indicate each position to be checked with an X, and each position not to be checked with a period (.) or a question mark (?) or an underscore (_). Example:
DEFINE DATA LOCAL 1 #NAME (A15) END-DEFINE ... IF #NAME = MASK (..XX) 'ABCD' ...
In the above example, it is checked whether the field #NAME contains CD in the third and fourth positions. Positions one and two are not checked. The length of the mask determines how many positions are to be checked. The mask is left-justified against any field or constant used in the mask operation. The format of the field (or constant) on the right side of the expression must be the same as the format of the field on the left side of the expression. If the field to be checked (operand1) is of format A, any constant used (operand2) must be enclosed in apostrophes. If the field is numeric, the value used must be a numeric constant or the content of a numeric database field or user-defined variable. In either case, any characters/digits within the value specified whose positions do not match the X indicator within the mask are ignored. The result of the MASK operation is true when the indicated positions in both values are identical. Example:
** Example 'LOGICX01': MASK option in logical condition ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY END-DEFINE * HISTOGRAM EMPLOY-VIEW CITY IF CITY =
426
Programming Guide
In the above example, the record will be accepted if the fifth and sixth positions of the field CITY each contain the character N.
Range Checks
When performing range checks, the number of positions verified in the supplied variable is defined by the precision of the value supplied in the mask specification. For example, a mask of (...193...) will verify positions 4 to 6 for a three-digit number in the range 000 to 193. Additional Examples of Mask Definitions:
In this example, positions 4 to 6 of #VALUE are to be checked for the value 123:
IF #VALUE(A10) = MASK (...'123')
This example will check if #LICENSE contains a license number which begins with NY- and whose last five characters are identical to the last five positions of #VALUE:
DEFINE DATA LOCAL 1 #VALUE(A8) 1 #LICENSE(A8) END-DEFINE INPUT 'ENTER KNOWN POSITIONS OF LICENSE PLATE:' #VALUE IF #LICENSE = MASK ('NY-'XXXXX) #VALUE
Programming Guide
427
The following condition would be met by any value which contains NAT and AL no matter which and how many other characters are between NAT and AL (this would include the values NATURAL and NATIONALITY as well as NATAL):
MASK('NAT'*'AL')
For further information about checking field contents, see MASK Option Compared with IS Option.
428
Programming Guide
'Assignment #N2 :=
12
results in:'
'Assignment #N2 :=
-1
results in:'
'Assignment #P3 :=
12
results in:'
'Assignment #P3 :=
-1
results in:'
DEFINE SUBROUTINE SUBTEST IF #A2 IS (N2) THEN #CONV-N2 := VAL(#A2) WRITE NOTITLE 12T '#A2 can be converted to' #CONV-N2 '(N2)' END-IF IF #A2 IS (P3) THEN #CONV-P3 := VAL(#A2) WRITE NOTITLE 12T '#A2 can be converted to' #CONV-P3 '(P3)' END-IF IF #N2 = MASK(NZ) THEN WRITE NOTITLE 12T '#N2 contains the valid unpacked number' #N2 END-IF IF #P3 = MASK(NNZ) THEN WRITE NOTITLE 12T '#P3 contains the valid packed number' #P3 END-IF END-SUBROUTINE * END
Programming Guide
429
12
Assignment #A2 := '-1' results in: #A2 can be converted to #A2 can be converted to Assignment #N2 #A2 #A2 #N2
-1 (N2) -1 (P3)
:= 12 results in: can be converted to 12 (N2) can be converted to 12 (P3) contains the valid unpacked number
12
Assignment #N2 := -1 results in: #N2 contains the valid unpacked number Assignment #P3 := 12 results in: #P3 contains the valid packed number Assignment #P3 := -1 results in: #P3 contains the valid packed number
-1
12
-1
This option is used to determine whether the content of a field has been modified during the execution of an INPUT or PROCESS PAGE statement. As a precondition, a control variable must have been assigned using the parameter CV. Operand Definition Table:
Operand
operand1
Possible Structure S A
Possible Formats C
Attribute control variables referenced in an INPUT or PROCESS PAGE statement are always assigned the status not modified when the map is transmitted to the terminal. Whenever the content of a field referencing an attribute control variable is modified, the attribute control variable has been assigned the status modified. When multiple fields reference the same attribute control variable, the variable is marked modified if any of these fields is modified.
430
Programming Guide
Logical Condition Criteria If operand1 is an array, the result will be true if at least one of the array elements has been assigned the status modified (OR operation). The Natural profile parameter CVMIN may be used to determine if an attribute control variable is also to be assigned the status modified if the value of the corresponding field is overwritten by an identical value. Example of MODIFIED Option:
** Example 'LOGICX06': MODIFIED option in logical condition ************************************************************************ DEFINE DATA LOCAL 1 #ATTR (C) 1 #A (A1) 1 #B (A1) END-DEFINE * MOVE (AD=I) TO #ATTR * INPUT (CV=#ATTR) #A #B IF #ATTR NOT MODIFIED WRITE NOTITLE 'FIELD #A OR #B HAS NOT BEEN MODIFIED' END-IF * IF #ATTR MODIFIED WRITE NOTITLE 'FIELD #A OR #B HAS BEEN MODIFIED' END-IF * END
#A
#B
After entering any value and pressing ENTER, the following output is displayed:
FIELD #A OR #B HAS BEEN MODIFIED
Programming Guide
431
operand1
SCAN
operand2 (operand2)
operand1 C S A operand2 C S
*
operand2 may only be binary if operand1 is of format A or U. If operand1 is of format U and op-
The SCAN option is used to scan for a specific value within a field. The characters used in the SCAN option (operand2) may be specified as an alphanumeric or Unicode constant (a character string bounded by apostrophes) or the contents of an alphanumeric or Unicode database field or user-defined variable. Caution: Trailing blanks are automatically eliminated from operand1 and operand2. Therefore, the SCAN option cannot be used to scan for values containing trailing blanks. operand1 and operand2 may contain leading or embedded blanks. If operand2 consists of blanks only, scanning will be assumed to be successful, regardless of the value of operand1; confer EXAMINE FULL statement if trailing blanks are not to be ignored in the scan operation. The field to be scanned (operand1) may be of format A, N, P or U. The SCAN operation may be specified with the equal (EQ) or not equal (NE) operators. The length of the character string for the SCAN operation should be less than the length of the field to be scanned. If the length of the character string specified is identical to the length of the field to be scanned, then an EQUAL operator should be used instead of SCAN.
432
Programming Guide
Programming Guide
433
This option is used to check whether an optional parameter in an invoked object (subprogram or external subroutine) has received a value from the invoking object or not. An optional parameter is a field defined with the keyword OPTIONAL in the DEFINE DATA PARAMETER statement of the invoked object. If a field is defined as OPTIONAL, a value can - but need not - be passed from an invoking object to this field. In the invoking statement, the notation nX is used to indicate parameters for which no values are passed. If you process an optional parameter which has not received a value, this will cause a runtime error. To avoid such an error, you use the SPECIFIED option in the invoked object to check whether an optional parameter has received a value or not, and then only process it if it has.
parameter-name is the name of the parameter as specified in the DEFINE DATA PARAMETER statement
of the invoked object. For a field not defined as OPTIONAL, the SPECIFIED condition is always TRUE. Example of SPECIFIED Option: Calling Programming:
** Example 'LOGICX07': SPECIFIED option in logical condition ************************************************************************ DEFINE DATA LOCAL 1 #PARM1 (A3) 1 #PARM3 (N2) END-DEFINE * #PARM1 := 'ABC' #PARM3 := 20 * CALLNAT 'LOGICX08' #PARM1 1X #PARM3 * END
434
Programming Guide
Programming Guide
435
436
53
Field Initialization ........................................................................................................................... 438 Data Transfer ................................................................................................................................ 438 Field Truncation and Field Rounding .................................................................................................. 441 Result Format and Length in Arithmetic Operations .............................................................................. 441 Arithmetic Operations with Floating-Point Numbers .............................................................................. 442 Arithmetic Operations with Date and Time .......................................................................................... 444 Performance Considerations for Mixed Format Expressions ................................................................... 448 Precision of Results for Arithmetic Operations ..................................................................................... 448 Error Conditions in Arithmetic Operations ........................................................................................... 449 Processing of Arrays ...................................................................................................................... 450
437
Field Initialization
A field (user-defined variable or database field) which is to be used as an operand in an arithmetic operation must be defined with one of the following formats:
Format N Numeric unpacked P I F T Packed numeric Integer Floating point Time
D Date
Note: For reporting mode: A field which is to be used as an operand in an arithmetic operation must have been previously defined. A user-defined variable or database field used as a result field in an arithmetic operation need not have been previously defined. All user-defined variables and all database fields defined in a DEFINE DATA statement are initialized to the appropriate zero or blank value when the program is invoked for execution.
Data Transfer
Data transfer is performed with a MOVE or COMPUTE statement. The following table summarizes the data transfer compatibility of the formats an operand may take.
Sending Field Format N or P N or P A U Bn (n<5) Bn (n>4) I L C Y [4] Y A [2] Y [ 11 ] [2] [6] [2] [9] U [ 14 ] [ 13 ] Y [ 14 ] [ 15 ] [ 14 ] [ 16 ] Receiving Field Format Bn (n<5) Bn (n>4) [3] [1] [ 12 ] [5] [5] [3] [1] [ 12 ] [5] [5] I L C D Y - - - - - Y - - - Y - - Y - - Y T F G O Y Y - - - - - - - Y Y - - - - Y Y - - - - - - - -
438
Programming Guide
Y - - [8] Y Y - -
[ 9 ] [ 10 ] [ 10 ] [ 16 ]
Where:
Y indicates data transfer compatibility. indicates data transfer incompatibility.
[ ] brackets [ ] refer to the corresponding rule for data transfer given below.
Data Conversion
The following rules apply to converting data values: 1. Alphanumeric to binary: The value will be moved byte by byte from left to right. The result may be truncated or padded with trailing blank characters depending on the length defined and the number of bytes specified. 2. (N,P,I) and binary (length 1-4) to alphanumeric: The value will be converted to unpacked form and moved into the alphanumeric field left justified, i.e., leading zeros will be suppressed and the field will be filled with trailing blank characters. For negative numeric values, the sign will be converted to the hexadecimal notation Dx. Any decimal point in the numeric value will be ignored. All digits before and after the decimal point will be treated as one integer value. 3. (N,P,I,F) to binary (1-4 bytes): The numeric value will be converted to binary (4 bytes). Any decimal point in the numeric value will be ignored (the digits of the value before and after the decimal point will be treated as an integer value). The resulting binary number will be positive or a two's complement of the number depending on the sign of the value. 4. Binary (1-4 bytes) to numeric: The value will be converted and assigned to the numeric value right justified, i.e., with leading zeros. (Binary values of the length 1-3 bytes are always assumed to have a positive sign. For binary values of 4 bytes, the leftmost bit determines the sign of the number: 1=negative, 0=positive.) Any decimal point in the receiving numeric value will be ignored. All digits before and after the decimal point will be treated as one integer value. 5. Binary to binary: The value will be moved from right to left byte by byte. Leading binary zeros will be inserted into the receiving field.
Programming Guide
439
Rules for Arithmetic Assignment 6. Binary (>4 bytes) to alphanumeric: The value will be moved byte by byte from left to right. The result may be truncated or padded with trailing blanks depending on the length defined and the number of bytes specified. 7. Date (D) to time (T): If date is moved to time, it is converted to time assuming time 00:00:00:0. 8. Time (T) to date (D): If time is moved to date, the time information is truncated, leaving only the date information. 9. L,D,T,F to A: The values are converted to display form and are assigned left justified. 10. F: If F is assigned to an alphanumeric or Unicode field which is too short, the mantissa is reduced accordingly. 11. Unicode to alphanumeric: The Unicode value will be converted to alphanumeric character codes according to the default code page (value of the system variable *CODEPAGE) using the International Components for Unicode (ICU) library. The result may be truncated or padded with trailing blank characters, depending on the length defined and the number of bytes specified. If the characters of the Unicode value are not defined in the default code page, a runtime error is output or the characters are replaced with the substitution character, depending on the setting of the profile/session parameter CPCVERR. 12. Unicode to binary: The value will be moved code unit by code unit from left to right. The result may be truncated or padded with trailing blank characters, depending on the length defined and the number of bytes specified. The length of the receiving binary field must be even. 13. Alphanumeric to Unicode: The alphanumeric value will be converted from the default code page to a Unicode value using the International Components for Unicode (ICU) library. The result may be truncated or padded with trailing blank characters, depending on the length defined and the number of code units specified. 14. (N,P,I) and binary (length 1-4) to Unicode: The value will be converted to unpacked form from which an alphanumeric value will be obtained by suppression of leading zeros. For negative numeric values, the sign will be converted to the hexadecimal notation Dx. Any decimal point in the numeric value will be ignored. All digits before and after the decimal point will be treated as one integer value. The resulting value will be converted from alphanumeric to Unicode. The result may be truncated or padded with trailing blank characters, depending on the length defined and the number of code units specified. 15. Binary (>4 bytes) to Unicode: The value will be moved byte by byte from left to right. The result may be truncated or padded with trailing blanks, depending on the length defined and the number of bytes specified. The length of the sending binary field must be even.
440
Programming Guide
Rules for Arithmetic Assignment 16. L,D,T,F to U: The values are converted to an alphanumeric display form. The resulting value will be converted from alphanumeric to Unicode and assigned left justified. If source and target format are identical, the result may be truncated or padded with trailing blank characters (format A and U) or leading binary zeros (format B) depending on the length defined and the number of bytes (format A and B) or code units (format U) specified. See also Using Dynamic Variables.
High-order numeric field truncation is allowed only when the digits to be truncated are leading zeros. Digits following an expressed or implied decimal point may be truncated. Trailing positions of an alphanumeric field may be truncated. If the option ROUNDED is specified, the last position of the result will be rounded up if the first truncated decimal position of the value being assigned contains a value greater than or equal to 5. For the result precision of a division, see also Precision of Results for Arithmetic Operations.
N or P P* P* P* P*
On a mainframe computer, format/length F8 is used instead of F4 for improved precision of the results of an arithmetic operation. P* is determined from the integer length and precision of the operands individually for each operation, as shown under Precision of Results for Arithmetic Operations.
Programming Guide
441
Rules for Arithmetic Assignment The following decimal integer lengths and possible values are applicable for format I:
Format/Length Decimal Integer Length Possible Values I1 I2 I4 3 5 10 -128 to 127 -32 768 to 32 767 -2 147 483 648 to 2 147 483 647
General Considerations Precision of Floating-Point Numbers Conversion to Floating-Point Representation Platform Dependency
General Considerations
Floating-point numbers (format F) are represented as a sum of powers of two (as are integer numbers (format I)), whereas unpacked and packed numbers (formats N and P) are represented as a sum of powers of ten. In unpacked or packed numbers, the position of the decimal point is fixed. In floating-point numbers, however, the position of the decimal point (as the name indicates) is floating, that is, its position is not fixed, but depends on the actual value. Floating-point numbers are essential for the computing of trigonometric functions or mathematical functions such as sinus or logarithm.
For a variable of format/length F4, the precision is limited to approximately 7 digits. For a variable of format/length F8, the precision is limited to approximately 16 digits.
Values which have more significant digits cannot be represented exactly as a floating-point number. No matter how many additional digits there are before or after the decimal point, a floating-point number can cover only the leading 7 or 16 digits respectively. An integer value can only be represented exactly in a variable of format/length F4 if its absolute value does not exceed 2 24 -1.
442
Programming Guide
1.25 = 2 + 2
-2
1.2 = 2 + 2
-3
+ 2
-4
+ 2
-7
+ 2
-8
+ 2
-11
+ 2
-12
+ ...
Thus, the conversion of alphanumeric, unpacked numeric or packed numeric values to floatingpoint values, and vice versa, can introduce small errors. Note: If an integer, unpacked or packed result of an arithmetic operation (see Result Format and Length in Arithmetic Operations) has to be converted to floating point representation, you should consider to perform the arithmetic operation already in floating point format to improve the precision. Example:
#F1 (F8) := 1 / 12 #F2 (F8) := 1.0E0 / 12 /* Result is +8.333330000000000E-02 /* Result is +8.333333333333333E-02
Platform Dependency
Because of different hardware architecture, the representation of floating-point numbers varies according to platforms. This explains why the same application, when run on different platforms, may return slightly different results when floating-point arithmetics are involved. The respective representation also determines the range of possible values for floating-point variables, which is (approximately) 5.4 * 10-79 to 7.2 * 1075 for F4 and F8 variables. Note: The representation used by your pocket calculator may also be different from the one used by your computer - which explains why results for the same computation may differ.
Programming Guide
443
The above statement is resolved as: 1. intermediate-result = operand1 +/- operand2 2. result-field = intermediate-result That is, in a first step Natural computes the result of the addition/subtraction, and in a second step assigns this result to the result field. More complex arithmetic operations are resolved following the same pattern:
COMPUTE result-field = operand1 +/- operand2 +/- operand3 +/- operand4
The above statement is resolved as: 1. intermediate-result1 = operand1 +/- operand2 2. intermediate-result2 = intermediate-result1 +/- operand3 3. intermediate-result3 = intermediate-result2 +/- operand4 4. result-field = intermediate-result3
444
Programming Guide
Rules for Arithmetic Assignment The resolution of multiplication and division operations is similar to the resolution for addition and subtraction. The internal format of such an intermediate-result depends on the formats of the operands, as shown in the tables below. Addition The following table shows the format of the intermediate result of an addition (intermediateresult = operand1 + operand2):
Format of operand1 Format of operand2 Format of intermediate-result D D D T Di, Ti, N, P, I Di, Ti, N, P, I Di, N, P, I Ti, N, P, I Di Ti D T Di, Ti, N, P, I D, T, Di, Ti, N, P, I D T Di Ti Ti, N, P, I Di, N, P, I Di T D T D T Di Ti Di Ti
Subtraction The following table shows the format of the intermediate result of a subtraction (intermediateresult = operand1 - operand2):
Format of operand1 Format of operand2 Format of intermediate-result D D D T T Di, N, P, I Di, N, P, I Di Ti N, P, I D T Di, Ti, N, P, I D, T Di, Ti, N, P, I D T Di, Ti, N, P, I D, T, Di, Ti, N, P, I Di, Ti Di Ti D Ti T Di Ti Di Ti P12
Programming Guide
445
Rules for Arithmetic Assignment Multiplication or Division The following table shows the format of the intermediate result of a multiplication (intermediateresult = operand1 * operand2) or division (intermediate-result = operand1 / operand2):
Format of operand1 Format of operand2 Format of intermediate-result D D T Di Di Ti Ti N, P, I N, P, I D, Di, Ti, N, P, I T D, T, Di, Ti, N, P, I T D, Di, Ti, N, P, I D Di, T, Ti, N, P, I D, Di T, Ti Di Ti Ti Ti Di Di Ti Di Ti
Internal Assignments Di is a value in internal date format; Ti is a value in internal time format; such values can be used in further arithmetic date/time operations, but they cannot be assigned to a result field of format D (see the assignment table below). In complex arithmetic operations in which an intermediate result of internal format Di or Ti is used as operand in a further addition/subtraction/multiplication/division, its format is assumed to be D or T respectively. The following table shows which intermediate results can internally be assigned to which result fields (result-field = intermediate-result).
Format of result-field Format of intermediate-result D D T N, P, I D, T Di, Ti, N, P, I D, T, Di, Ti, N, P, I D, T, Di, Ti, N, P, I Assignment possible yes no yes yes
446
Programming Guide
COMPUTE DATE1 (D) = DATE2 (D) + DATE3 (D) COMPUTE DATE1 (D) = DATE2 (D) - DATE3 (D)
These operations are not possible, because the intermediate result of the addition/subtraction would be format Di, and a value of format Di cannot be assigned to a result field of format D. Examples 3 and 4 (invalid):
COMPUTE DATE1 (D) = TIME2 (T) - TIME3 (T) COMPUTE DATE1 (D) = DATE2 (D) - TIME3 (T)
These operations are not possible, because the intermediate result of the addition/subtraction would be format Ti, and a value of format T i cannot be assigned to a result field of format D. Example 5 (valid):
COMPUTE DATE1 (D) = DATE2 (D) - DATE3 (D) + TIME3 (T)
This operation is possible. First, DATE3 is subtracted from DATE2, giving an intermediate result of format Di; then, this intermediate result is added to TIME3, giving an intermediate result of format T; finally, this second intermediate result is assigned to the result field DATE1. Examples 6 and 7 (invalid):
COMPUTE DATE1 (D) = DATE2 (D) + DATE3 (D) * 2 COMPUTE TIME1 (T) = TIME2 (T) - TIME3 (T) / 3
These operations are not possible, because the attempted multiplication/division is performed with date/time fields and not with intermediate results. Example 8 (valid):
COMPUTE DATE1 (D) = DATE2 (D) + (DATE3(D) - DATE4 (D)) * 2
This operation is possible. First, DATE4 is subtracted from DATE3 giving an intermediate result of format Di; then, this intermediate result is multiplied by two giving an intermediate result of format Di; this intermediate result is added to DATE2 giving an intermediate result of format D; finally, this third intermediate result is assigned to the result field DATE1. If a format T value is assigned to a format D field, you must ensure that the time value contains a valid date component.
Programming Guide
447
Addition/Subtraction Fi + 1 or Si + 1 (whichever is greater) Fd or Sd (whichever is greater) Multiplication Division Exponentiation Square Root Fi + Si + 2 Fi + Sd 15 - Fd (See Exception below) Fi Fd + Sd (maximum 7) (see below) Fd Fd
- where:
F First operand S Second operand R Result i Digits before decimal point d Digits after decimal point
Exception: If the exponent has one or more digits after the decimal point, the exponentiation is internally carried out in floating point format and the result will also have floating point format. See Arithmetic Operations with Floating-Point Numbers for further information.
448
Programming Guide
If a result field is available, the precision is: Rd or Fd (whichever is greater) *. If no result field is available, the precision is: Fd or Sd (whichever is greater) *.
If the ROUNDED option is used, the precision of the result is internally increased by one digit before the result is actually rounded. A result field is available (or assumed to be available) in a COMPUTE and DIVIDE statement, and in a logical condition in which the division is placed after the comparison operator (for example: IF #A = #B / #C THEN ...). A result field is not (or not assumed to be) available in a logical condition in which the division is placed before the comparison operator (for example: IF #B / #C = #A THEN ...). Exception: If both dividend and divisor are of integer format and at least one of them is a variable, the division result is always of integer format (regardless of the precision of the result field and of whether the ROUNDED option is used or not).
if the base is of packed format and either the result has over 16 digits or any intermediate result has over 15 digits; if the base is of floating-point format and the result is greater than approximately 7 * 1075.
Programming Guide
449
Processing of Arrays
Generally, the following rules apply:
All scalar operations may be applied to array elements which consist of a single occurrence. If a variable is defined with a constant value (for example, #FIELD (I2) CONSTANT <8>), the value will be assigned to the variable at compilation, and the variable will be treated as a constant. This means that if such a variable is used in an array index, the dimension concerned has a definite number of occurrences. If an assignment/comparison operation involves two arrays with a different number of dimensions, the missing dimension in the array with fewer dimensions is assumed to be (1:1). Example: If #ARRAY1 (1:2) is assigned to #ARRAY2 (1:2,1:2), #ARRAY1 is assumed to be #ARRAY1 (1:1,1:2).
Definitions of Array Dimensions Assignment Operations with Arrays Comparison Operations with Arrays Arithmetic Operations with Arrays
450
Programming Guide
If a single occurrence is assigned to an array range, each element of the range is filled with the value of the single occurrence. (For a mathematical function, each element of the range is filled with the result of the function.) Before an assignment operation is executed, the individual dimensions of the arrays involved are compared with one another to check if they meet one of the conditions listed below. The dimensions are compared independently of one another; that is, the 1st dimension of the one array is compared with the 1st dimension of the other array, the 2nd dimension of the one array is compared with the 2nd dimension of the other array, and the 3rd dimension of the one array is compared with the 3rd dimension of the other array. The assignment of values from one array to another is only allowed under one of the following conditions:
The number of occurrences is the same for both dimensions compared. The number of occurrences is indefinite for both dimensions compared. The dimension that is assigned to another dimension consists of a single occurrence.
Example - Array Assignments: The following program shows which array assignment operations are possible.
DEFINE DATA LOCAL 1 A1 (N1/1:8) 1 B1 (N1/1:8) 1 A2 (N1/1:8,1:8) 1 B2 (N1/1:8,1:8) 1 A3 (N1/1:8,1:8,1:8) 1 I (I2) INIT <4> 1 J (I2) INIT <8> 1 K (I2) CONST <8> END-DEFINE * COMPUTE A1(1:3) = B1(6:8)
/* allowed
Programming Guide
451
/* allowed /* allowed /* NOT ALLOWED /* NOT ALLOWED /* allowed /* allowed /* allowed /* allowed /* allowed /* NOT ALLOWED /* allowed /* allowed /* NOT ALLOWED
452
Programming Guide
The array dimensions compared with one another have the same number of occurrences. The array dimensions compared with one another have an indefinite number of occurrences. All array dimensions of one of the arrays involved are single occurrences.
Example - Array Comparisons: The following program shows which array comparison operations are possible:
DEFINE DATA LOCAL 1 A3 (N1/1:8,1:8,1:8) 1 A2 (N1/1:8,1:8) 1 A1 (N1/1:8) 1 I (I2) INIT <4> 1 J (I2) INIT <8> 1 K (I2) CONST <8> END-DEFINE * IF A2(1,1) = A1(1) IF A2(1,1) = A1(I) IF A2(1,*) = A1(1) IF A2(1,*) = A1(I) IF A2(1,*) = A1(*) IF A2(1,*) = A1(I -3:I+4) IF A2(1,5:J) = A1(1:I) IF A2(1,*) = A1(1:I) IF A2(1,*) = A1(1:K) * IF A2(1,1) = A2(1,1) IF A2(1,1) = A2(1,I) IF A2(1,*) = A2(1,1:8) IF A2(1,*) = A2(I,I -3:I+4) IF A2(1,1:I) = A2(1,I+1:J) IF A2(1,1:I) = A2(1,I:I+1) IF A2(*,1) = A2(1,*) IF A2(1,1:I) = A1(2,1:K) * IF A3(1,1,*) = A2(1,*) IF A3(1,1,*) = A2(1,I -3:I+4)
THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN THEN
IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE IGNORE
END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF END-IF
/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*
allowed allowed allowed allowed allowed allowed allowed NOT ALLOWED(NAT0629) allowed allowed allowed allowed allowed allowed NOT ALLOWED(NAT0629) NOT ALLOWED(NAT0629) NOT ALLOWED(NAT0629)
Programming Guide
453
When you compare two array ranges, note that the following two expressions lead to different results:
#ARRAY1(*) NOT EQUAL #ARRAY2(*) NOT #ARRAY1(*) = #ARRAY2(*)
Example:
Condition A:
IF #ARRAY1(1:2) NOT EQUAL #ARRAY2(1:2)
Condition A is therefore true if the first occurrence of #ARRAY1 does not equal the first occurrence of #ARRAY2 and the second occurrence of #ARRAY1 does not equal the second occurrence of #ARRAY2.
Condition B:
IF NOT #ARRAY1(1:2) = #ARRAY2(1:2)
Condition B is therefore true if either the first occurrence of #ARRAY1 does not equal the first occurrence of #ARRAY2 or the second occurrence of #ARRAY1 does not equal the second occurrence of #ARRAY2.
454
Programming Guide
In other words:
Array Dimension # # of Occurrences Range #c #c #a #a #b 2nd 1st 2nd 1st 1st 2 3 2 3 3 2:3 2:4 3:4 1:3 3:5
The operation is performed element by element. Note: An arithmetic operation of a different number of dimensions is allowed. For the example above, the following operations are executed:
#c(2,2) := #a(3,1) + #b(3) #c(2,3) := #a(3,2) + #b(4) #c(2,4) := #a(3,3) + #b(5) #c(3,2) := #a(4,1) + #b(3) #c(3,3) := #a(4,2) + #b(4) #c(3,4) := #a(4,3) + #b(5)
Below is a list of examples of how array ranges may be used in the following ways in arithmetic operations (in COMPUTE, ADD or MULTIPLY statements). In examples 1-4, the number of occurrences of the corresponding dimensions must be equal. 1. range + range = range. The addition is performed element by element. 2. range * range = range.
Programming Guide
455
Rules for Arithmetic Assignment The multiplication is performed element by element. 3. scalar + range = range. The scalar is added to each element of the range. 4. range * scalar = range. Each element of the range is multiplied by the scalar. 5. range + scalar = scalar. Each element of the range is added to the scalar and the result is assigned to the scalar. 6. scalar * range = scalar2. The scalar is multiplied by each element of the array and the result is assigned to scalar2. Since no intermediate results will be generated for arithmetic operations as shown in the examples 1-4, the format of the computed result (see Result Format and Length in Arithmetic Operations) must be the same as the format of the result operand (the formats P and N are considered to be the same). Example:
DEFINE DATA LOCAL 1 #ARRAYI4(I4/1:5) 1 #ARRAYP5(P5/1:5) END-DEFINE * #ARRAYI4(*) := #ARRAYP5(*) + 1
/* NOT ALLOWED(NAT0294)
Since no intermediate results will be generated for arithmetic operations as shown in the above examples, the result of overlapping index ranges is computed element by element. Example:
DEFINE DATA LOCAL 1 #ARRAY(I4/1:5) INIT <10,20,30,40,50> END-DEFINE * #ARRAY(3:5) := #ARRAY(2:4) + 1 /* is identical to /* #ARRAY(3) := #ARRAY(2) + 1 /* #ARRAY(4) := #ARRAY(3) + 1 /* #ARRAY(5) := #ARRAY(4) + 1 /* /* #ARRAY contains 10,20,21,22,23
456
Programming Guide
54
Compilation Aspects
Compiler Options and Parameters .................................................................................................... 458 Other Parameters Influencing the Compiler ......................................................................................... 459
457
Compilation Aspects Below is an overview of the compilation options and parameters that have an influence on how the completed source code is checked by the compiler and how it is generated into Natural internal object code that can be interpreted and executed by the Natural runtime system. For more information on the Natural compiler and the different system commands for compiling source code, see the section Natural Compiler in the Natural System Architecture documentation.
one or multiple OPTIONS statements (offering the same options as the COMPOPT system command and, in addition, Natural Optimizer Compiler options);
SET GLOBALS
458
Programming Guide
Compilation Aspects
Short Description Unicode and Code Page Support Default Code Page Name
Comment Output of Unicode constants in I/O statements (for example, WRITE U'ABC') is allowed only when CFICU=ON. Specifies the code page of the source.
Character for Decimal Point Character used for separating integer/precision digits when Notation defining fields of format N or P and constants. Format Specification Input Delimiter Character Line Size Allows or disallows the use of variables that were not defined before. For example, to delimit values in an INIT clause. Specifies the default size for a print line in a report (0 - 31). The setting can be overwritten by specifying an explicit FORMAT statement in the source code. Maximum number of lines that may be output by a single I/O statement (for example, WRITE). Non-compliance with the basic setting will cause an error. The setting can be overwritten by specifying an explicit FORMAT statement in the source code. Number of spaces to be inserted between field settings of columns on Natural reports created using a DISPLAY statement. The setting can be overwritten by specifying an explicit FORMAT statement in the source code.
PS
Page Size
SF
Spacing Factor
SOSI ZP
Shift-Out/Shift-In Codes for Specifies the shift characters to identify a double-byte character Double-Byte Character Set set (DBCS) string. Zero Printing Output of blanks or zeros for a numerical constant which contains a value of all zeros. The setting can be overwritten by specifying an explicit FORMAT statement in the source code.
Programming Guide
459
460
55
Statements Available ...................................................................................................................... 462 General Prerequisites ..................................................................................................................... 469 HTTPS Support for the REQUEST DOCUMENT Statement under z/OS ................................................... 472 Restriction Concerning IMS TM ........................................................................................................ 475 Preconditions for the Support of XML-Related Statements under openUTM ............................................... 475 Sample Program ........................................................................................................................... 476 Frequently Asked Questions ............................................................................................................ 479 References ................................................................................................................................... 486
461
Statements for Internet and XML Access This chapter gives a functional overview of the Natural statements for internet and XML access, specifies the general prerequisites for using these statements in a mainframe environment, informs about restrictions that apply and contains a list of further references. To take full advantage of these statements, a thorough knowledge of the underlying communication standards is required.
Statements Available
The following Natural statements are available for access to the internet and to XML documents:
REQUEST DOCUMENT
Functionality This statement enables you to use the Hypertext Transfer Protocol (HTTP) and - under z/OS only - the Hypertext Transfer Protocol Secure (HTTPS) in order to access documents on the web with a given Uniform Resource Identifier (URI) or Uniform Resource Locator (URL), that is, the internet or intranet address of a web site.
REQUEST DOCUMENT implements an HTTP client at Natural statement level, which allows applications
to access any HTTP server on either the intranet or the internet. The statement has a set of operands, which allows it to formulate HTTP requests according to the needs of the user application. For example, using outbound operands it is possible to send user-defined HTTP headers, form data, or entire documents to a HTTP server. The inbound operands can be used to retrieve a document from the server, to view the entire HTTP header block returned from the server, or to return the values of dedicated headers, etc. Via binary format operands, binary objects such as gif files can be exchanged with the http server as well. For basic authorization purposes, user ID and password operands can be specified. The content of this operand is sent with base64 encoding over the line, according to HTTP standards. Natural supports the following request methods:
GET
- retrieve a document and HTTP headers, - retrieve HTTP headers only, - transfer form data to an HTTP server,
462
Programming Guide
Statements for Internet and XML Access The request method is normally evaluated automatically, based on the operands coded for the executed REQUEST DOCUMENT statement. However, the predetermined request method can be overwritten by an explicit user specification of a request method header. Data transfer with the REQUEST DOCUMENT statement normally does not involve any code page conversion. If you want to have the outgoing and/or incoming data encoded in a specific code page, you can use the DATA ALL clause and/or the RETURN PAGE clause of the REQUEST DOCUMENT statement to specify this. In order to simplify data exchange from EBCDIC-based mainframes with HTTP servers, which in most cases work with UTF-8 or ISO-8859-1 encoded data, the statement provides ENCODED clauses to allow implicit or automatic conversion of outbound and inbound document data. Technical Implementation The implementation of the REQUEST DOCUMENT statement mainly consists of two layers:
an independent runtime layer, where the entire HTTP processing, URL analysis, data conversion, etc., is executed; and a layer where an environment-dependent routine processes the TCP/IP communication between Natural and the HTTP server. This layer is implemented based on LE (Language environment) sockets for z/OS, VSE, and VM/CMS; SMARTS sockets for Com-plete and Natural Development Server; and CRTE sockets for BS2000/OSD. For CICS, the appropriate socket library is included into the build process.
Natural for Mainframes supports the HTTP protocol version 1.0 only, meaning that no persistent connection to the server is maintained. Since virtually every corporate network processes access to the internet via a proxy server from the client, Natural can be configured with the adequate settings for the proxy server and the port on which the proxy server runs. Moreover, it is possible to specify local domain name suffixes (intranet sites), which shall be accessed directly instead via the proxy server. See also Overview of Applicable Natural Parameters. The proxy server, which is located between client (user) and internet, serves the following purposes: It receives the request from the clients, forwards it to the target server, caches the returned document and forwards it to the client. A proxy server is advantageous because of its improved performance, which is due to the caching, and because it helps to avoid security issues (most proxy servers are working as firewall as well).
Programming Guide
463
Statements for Internet and XML Access The following is an example of how the REQUEST DOCUMENT statement can be used to access an externally-located document:
REQUEST DOCUMENT FROM "http://bolsap1:5555/invoke/sap.demo/handle_RFC_XML_POST" WITH USER #User PASSWORD #Password DATA NAME 'XMLData' VALUE #Queryxml NAME 'repServerName' VALUE 'NT2' RETURN PAGE #Resultxml RESPONSE #rc
Syntax The syntax of the REQUEST DOCUMENT statement and detailed application hints are to be found in the Statements documentation. Platform Support for REQUEST DOCUMENT The REQUEST DOCUMENT statement is supported on the following mainframe platforms:
z/OS: Batch, TSO, CICS, Com-plete, IMS TM z/VSE: Batch, Com-plete, CICS VM/CMS BS2000/OSD: Batch, TIAM, openUTM *
* See also Preconditions for the Support of XML-Related Statements under openUTM below. Moreover this statement is available on all OpenSystems platforms that are supported by Natural.
PARSE XML
Functionality Technical Implementation Processing of XML Whitespace Characters and Predefined Entities Syntax
464
Programming Guide
Functionality The PARSE XML statement allows you to parse XML documents from within a Natural program. The PARSE XML statement integrates a full XML parser into Natural, thus allowing Natural applications to parse XML documents in order to easily process their content. The PARSE XML statement opens a processing loop and returns, whenever one of a list of events occurs during the parse process, the respective path through the document, name and value of parsed elements together with some parser status system variables. Technical Implementation For parsing XML documents the following parsing strategies or models are most common:
DOM (Document Object Model), an object oriented approach SAX (Simple Access to XML), a stream-oriented parsing method
The implementation of the PARSE XML statement in Natural for Mainframes is based on the SAX method, using a mainframe port of version 2.0.0 of the (open source) SAX parser EXPAT. Parsing is processed internally on a UTF-16 encoded image of the document to parse, that is, if the document is not delivered in this encoding, an internal conversion to UTF-16 is performed before the parsing starts. This has to be considered at Natural installation time, for example, when the thread size for the TP environment is evaluated. The encoding of the document to parse is checked automatically. 1. A check for a BOM (Byte Order Mark), which marks the document's encoding, is done. 2. If no BOM is found, a check for ASCII, EBCDIC, or UTF-16 (BE or LE: big endian or little endian) is done. 3. If an EBCDIC or ASCII encoding is identified, a search for an encoding processing instruction is performed. If no encoding can be identified, an adequate error message is issued and the parse process is terminated. Internally, the parser works with UTF-16BE, so the document to parse is always converted to this encoding before it is passed to the EXPAT parser. 4. If an encoding PI (Processing Instruction) is found, the following defaults apply:
for ASCII, UTF-8 is assumed as encoding for EBCDIC, the Natural default code page (see system variable *CODEPAGE) is assumed as encoding
Programming Guide
465
In the first phase, the parser is called repeatedly to announce a well-defined set of callback entries. Those entries are entered by the parser whenever a corresponding element is encountered in the current parsed document. The occurrence of a start tag is, for instance, such an event which triggers a callback to the corresponding entry. The callback entries expose the Natural runtime logic for the execution of the parse process. The second phase is the actual parse process. The parser is called with the document to parse as input operand. Now, each element is parsed, and for each element type its corresponding callback routine is called. The Natural runtime then processes the returned element, updates the return operands, and enters the parse loop for processing those operands. Then the parser is restarted to continue the parse process. The parse process is finished either if the document is completely parsed or if an XML syntax error occurs in the current document, meaning the document is not well formed. Note: For technical reasons, nested parse loops are not supported in Natural for Mainframes.
Processing of XML Whitespace Characters and Predefined Entities As of Natural Version 4.2.5, parsing of character data does not cause a break or a loop path if the parsed string contains whitespace characters or predefined XML entities. This problem with Natural versions prior to Version 4.2.5 has been solved. With Natural Version 4.2.5, parsing of character data is compatible with Natural for Windows, UNIX and Linux. The outputs from the following sample program show the difference between Version 4.2.5 and its predecessors.
DEFINE DATA LOCAL 1 PAGE (A) DYNAMIC 1 #PATH (A200) 1 #NAME (A) DYNAMIC 1 #VALUE (A40) 1 #CMX (A) DYNAMIC 1 #CMP (A) DYNAMIC END-DEFINE FORMAT PS=60 LS=80 COMPRESS ' A<B ' H'0D0D' ' B<C' INTO #CMX LEAVING NO MOVE ALL #CMX TO #CMP UNTIL 16 COMPRESS '<?xml version="1.0" ?>' '<character-data-sample>' '<string_with_whitespace_and_predefined_entity>' #CMX '</string_with_whitespace_and_predefined_entity>' '</character-data-sample>' INTO PAGE LEAVING NO PARSE XML PAGE INTO PATH #PATH NAME #NAME VALUE #VALUE PRINT #PATH / 'NA=' #NAME / 'VA=' #VALUE
466
Programming Guide
character-data-sample NA= character-data-sample VA= character-data-sample/string_with_whitespace_and_predefined_entity NA= string_with_whitespace_and_predefined_entity VA= character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= A character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= < character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= B character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= ? character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= ? NA= VA= B character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= ? character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= ? character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= B character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= < character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= C character-data-sample/string_with_whitespace_and_predefined_entity// NA= string_with_whitespace_and_predefined_entity VA= character-data-sample// NA= character-data-sample VA= MORE
Programming Guide
467
Statements for Internet and XML Access Output if the program is executed in Natural Version 4.2.5 (or higher):
Page 1 08-11-04 13:41:34
character-data-sample NA= character-data-sample VA= character-data-sample/string_with_whitespace_and_predefined_entity NA= string_with_whitespace_and_predefined_entity VA= character-data-sample/string_with_whitespace_and_predefined_entity/$ NA= VA= A<B?? B<C character-data-sample/string_with_whitespace_and_predefined_entity// NA= string_with_whitespace_and_predefined_entity VA= character-data-sample// NA= character-data-sample VA=
MORE
Syntax The syntax of the PARSE XML statement and detailed application hints are to be found in the Statements documentation. Platform Support for PARSE XML The PARSE XML statement is supported on the following mainframe platforms:
z/OS: Batch, TSO, CICS, Com-plete, IMS TM * z/VSE: Batch, Com-plete, CICS VM/CMS BS2000/OSD: Batch, TIAM, openUTM **
* See Restriction Concerning IMS TM below. * * See also Preconditions for the Support of XML-Related Statements under openUTM below. Moreover this statement is available on all Open Systems platforms that are supported by Natural.
468
Programming Guide
General Prerequisites
This section describes the general prerequisites that apply if you wish to use the Natural statements REQUEST DOCUMENT and PARSE XML.
Installation Prerequisites
To enable the use of the Natural statements REQUEST DOCUMENT and PARSE XML, the installation steps described in the Installation documentation must be performed; Installation Steps for REQUEST DOCUMENT and PARSE XML. Since REQUEST DOCUMENT as well as PARSE XML, at least internally, always have to convert data from one encoding to another, Natural has to be driven with active ICU support. Therefore, the ICU library must be installed. If REQUEST DOCUMENT or PARSE XML is to be executed, the following prerequisites must be fulfilled:
a TCP/IP stack must be available and enabled for the execution environment, a DNS (Domain Name System) server or DNS services must be available in the execution environment to resolve internet address resolution requests (gehthostbyname function), a Natural driver must be installed LE enabled (in IBM environments) or CRTE enabled (in BS2000/OSD environments), support of HTTPS under Com-plete requires APS Version 2.7.2 Patch Level 16.
Profile Settings
Overview of Applicable Natural Parameters The following is an overview of Natural profile and/or session parameters that enable/disable or influence the support of the statements REQUEST DOCUMENT and/or PARSE XML:
Programming Guide
469
This Natural profile parameter and/or the corresponding parameter macro NTXML in conjunction with their keyword subparameters are used to activate/deactivate the statements REQUEST DOCUMENT and PARSE XML. In addition, there are various options that can be set with the keyword subparameters of NTXML and XML, such as separate enabling/disabling of support of the REQUEST DOCUMENT and PARSE XML statements, name of the default code page, URL of the (intranet) proxy server, port number of the proxy, URL and port number of the (intranet) SSL proxy server, and name(s) local domain(s) which are to be addressed directly. As a prerequisite for using the XML profile parameter, the profile parameter CFICU must be set to ON.
CFICU CP
This Natural profile parameter and/or the corresponding parameter macro NTCFICU in conjunction with their keyword subparameters are used to enable Unicode and code page support. This Natural profile parameter defines the default code page for Natural data and Natural sources. converting results in a Natural error or not.
CPCVERR This Natural profile and session parameter specifies whether a conversion error that occurs when
For further information on these parameters, see the corresponding sections in Parameter Reference documentation.
Activation/Deactivation
To activate the support of the statements REQUEST DOCUMENT and PARSE XML for the current session 1 To activate both statements together, set the Natural profile parameter XML (or the corresponding parameter macro NTXML) and also its keyword subparameters RDOC and PARSE to ON. Or: To activate the support individually, set only the corresponding XML/NTXML keyword subparameter to ON:
RDOC to enable support of REQUEST DOCUMENT PARSE to enable support of PARSE XML
If the installation platform operates behind an internet firewall or if the internet traffic is routed via a proxy server, the XML/NTXML keyword subparameters for proxy and proxyport have to be specified accordingly.
470
Programming Guide
To activate the support of the statements REQUEST DOCUMENT and PARSE XML for all sessions
Ask your system administrator to add the parameters and/or macros listed in the Overview of Applicable Natural Parameters to the Natural parameter module NATPARM and to set the values correspondingly. To deactivate the support of the statements REQUEST DOCUMENT and PARSE XML
To activate both statements together, set the Natural profile parameter XML or the parameter macro NTXML to OFF. Or: To deactivate the support individually, set only the corresponding XML/NTXML keyword subparameter to OFF:
RDOC to disable support of REQUEST DOCUMENT PARSE to disable support of PARSE XML
For information, see XML - Activate PARSE XML and REQUEST DOCUMENT Statements in the Parameter Reference documentation
Unicode Support
To enable Unicode support
For information on the various options that can be set with the keyword subparameters of profile parameter CFICU, see CFICU - Unicode Support in the Parameter Reference documentation. See also the paragraphs relating to the statements PARSE XML and REQUEST DOCUMENT in the section Statements, which is part of the section Unicode and Code Page Support in the Natural Programming Language in the Unicode and Code Page Support documentation.
Programming Guide
471
Short Introduction to HTTPS HTTPS over AT-TLS Maintenance of Certificates under z/OS Using RACF Key Rings Using Key Databases
Application layer HTTP(S) Security layer Transport layer Network layer TLS/SSL TCP IP
It was introduced to enable encryption and communication partner authentication for a secure data communication over the internet. The HTTPS URI scheme is used to indicate, that the HTTP communication is secured. For the encryption of the data the SSL (Secure Socket Layer) protocol or its successor TLS (Transport Layer Security) is used. Authentication is hereby provided by the exchange of certificates, which guarantee the identity of the communication partners. In most cases of HTTPS communication, however, only the server identifies itself with a certificate against the client. Client authentication with a client certificate occurs quite seldom. SSL communication is established in several steps:
It starts with identification and authentication of the communication partners over the so called SSL handshake protocol (Client Hello, Server Hello). The handshake is followed by the exchange of a symmetric session key via asymmetric encryption (private public key proceeding). The public key, which is hereby used by the client, is an essential part of the server certificate. After the handshake and key exchange have been performed, the encrypted payload request messages are communicated. The symmetric session key, which was negotiated in the preceding steps, is used for the encryption/decryption of those messages.
472
Programming Guide
Statements for Internet and XML Access The HTTPS protocol uses port numbers which differ from the standard HTTP port numbers. While HTTP normally uses port 80, the default port number for HTTPS is 443. HTTP access to the internet from a client, which is connected to a LAN (Local Area Network), is normally processed via special HTTP servers, so called proxies. Proxies are gateways to the internet from the LAN, which perform security policies, provide caches and validation routines or filter functions and act as firewalls. HTTPS secured internet access is most often performed over a proxy server of its own, which maintains the connections to the remote servers. This proxy is also known as SSL proxy. Certificates are binary documents, which contain, among other information items, information about the owner and the issuer of the certificate, the public key for the encryption of the session key data, an expiration date and a digital signature. The certificates, which are presented by HTTPS servers, are normally the lowest link of an entire chain of certificates. Such a certificate chain is called a Public Key Infrastructure (PKI). The certificate on top of such a chain is called a root certificate. Root certificates are generally issued by special organizations, named Certificate Authorities (CA). Root certificates, which are issued and signed by a CA are also called CA (root) certificates. For further information, see HTTP Developers Manual and other sources in the internet.
Basic The sockets application runs without modification in transparent mode, unaware of performing encrypted communication via AT-TLS. Thus legacy applications can run in secured mode without source code modification.
Aware The application is aware of running in secured mode and is able to query TLS status information.
Controlling The sockets application is aware of AT-TLS and controls the use of AT-TLS encryption services itself. This means, the application is able to switch between secured and non secured communication.
Programming Guide
473
Statements for Internet and XML Access Natural for Mainframes uses Controlling mode to switch on secured mode for HTTPS requests only, while HTTP requests remain unencrypted.
474
Programming Guide
The PARSE XML statement can be executed under the TP monitor IMS TM with the restriction that no I/O statement is allowed within an active PARSE loop. If an I/O occurs within a PARSE loop, error NAT0967 is issued.
For further restrictions, see the corresponding notes in the statement descriptions.
b. Define the maximum number of UTM tasks for PGWT calls. Example:
MAX TASKS-IN-PGWT=1
c. PGWT can be controlled using either the TAC-PRIORITIES instruction or the TACCLASS concept:
Programming Guide
475
3. The keyword subparameter ILCS of parameter macro NURENT must be set to ILCS=CRTE.
Sample Program
The following sample program shows the usage of the REQUEST DOCUMENT and the PARSE XML statement. Further sample programs are provided at the end of the description of each statement and in the Natural library SYSEXV.
DEFINE DATA LOCAL 1 #FROM (A) DYNAMIC 1 #HEADER (A) DYNAMIC 1 #PAGE (A) DYNAMIC 1 #RC (I4) 1 #COL (N8) 1 #COL1 (I4) 1 #COL2 (I4) 1 #COL3 (I4) 1 #LOC (A30) 1 #CP (A) DYNAMIC 1 #PATH (A) DYNAMIC 1 #NAME (A) DYNAMIC 1 #VALUE (A) DYNAMIC 1 #RTERR (I4) END-DEFINE * ASSIGN #FROM = 'HTTP://SI15.HQ.SAG/autos6.xml' **
476
Programming Guide
Note: The URL accessed in the above program addresses an intranet site and cannot be accessed from the internet. Output of the sample program:
HTTP/1.1 200 OK?Date: Thu, 10 Aug 2006 16:26:22 GMT?Server: Apache/1.3.19 ( BS2000)?Last-Modified: Thu, 27 Jul 2006 16:44:42 GMT?ETag: "2602c-111-44c8ed7a" ?Accept-Ranges: bytes?Content-Length: 273?Connection: close?Content-Type: text/ xml?? _______________________________________________________________________________ <?xml version="1.0" encoding="ISO-8859-1" ?><autos>?<make></make>?<make>Ford</ make>?<model>Thunderbird</model>?<make>Merceds-Benz</make><model>S400</model>< make>BWM</make><model version="latest">330I</model>?<make><label><company> Mercedes</company></label></make>?</autos>?
Programming Guide
477
478
Programming Guide
Why needs code page support to be enabled? How to use the XML keyword subparameters (e.g. RDP and RDNOP) How to determine proxy server, port number and HTTP server at a site? How to decide if a problem is a TCP/IP or HTTP issue or if it is a Natural issue? How can I check if I can reach a website from my mainframe without using Natural? Is NAT2TCP correctly loaded? I get a message "unsupported coding" How to avoid Natural error NAT3411 with REQUEST DOCUMENT? Can I use self-signed certificates? Which is the preferable method for maintaining certificates? How to configure TCP/IP for AT-TLS? How to verify AT-TLS configuration? Is there more information about problem determination? How to switch on P-agent trace? Error at connection establishment
Programming Guide
479
How to use the XML keyword subparameters (e.g. RDP and RDNOP)
On the PC, the REQUEST DOCUMENT statement executes the Internet Explorer and uses the settings as defined there. On the mainframe, the URL of the (intranet) proxy server through which all requests have to be routed has to be specified with the NTXML/XML keyword subparameter RDP. With the keyword subparameter RDNOP, local domain(s) which are to be addressed directly, not via the proxy server can be defined.
How to determine proxy server, port number and HTTP server at a site?
Information about proxy server, port number and HTTP server at a site has to be provided by the network administrator. You can also look into your browser which proxy server is defined for your site. For example, in the Internet Explorer under: Tools > Internet Options > Lan Settings > Advanced You can also search the web for tools which provide such information. For example (untested): http://www.sharewareconnection.com/titles/proxy-settings.htm
See buffer RDOCWA at Offset 480 Quite often these errors are ICU errors: Recommendation is to set profile or session parameter CPCVERR to OFF.
480
Programming Guide
How can I check if I can reach a website from my mainframe without using Natural?
To determine if a problem is related to the Natural installation or if there is a more general problem, you can do a PING from within TSO. For example, in the TSO command shell enter:
TSO PING www.google.com
This returns:
CS V1R9: Pinging host WWW.GOOGLE.COM (66.249.91.99) Ping #1 response took 0.018 seconds.
From within the Natural session you then can test the access to this website with the following small program. For example, start Natural with:
NATvr CFICU=ON XML=(ON,RDOC=ON,PARSE=ON,RDP='HTTPPROX.HQ.SAG',RDPPORT=8080,RDNOP='*.EUR.AD.SAG; *.HQ.SAG;*.SOFTWAREAG.COM')
where vr stands for the Natural release and version number. These values from an internal environment and a profile were used to store it. You have to get your settings for the keyword subparameters RDP, RDPPORT and RDNOP from your network administrator, or try the values as defined in your browser (Internet Explorer). Execute:
DEFINE DATA LOCAL 1 #RESULTXML (A) DYNAMIC 1 #RC (I4) END-DEFINE REQUEST DOCUMENT FROM "HTTP://WWW.GOOGLE.DE" RETURN HEADER ALL #HEADER RESPONSE #RC WRITE #RC WRITE #HEADER (AL=79) END
Programming Guide
481
482
Programming Guide
Statements for Internet and XML Access The Sample Policy Agent file defines all outgoing connections as application controlled TLS. This should not affect any other TCP/IP application except the Natural REQUEST DOCUMENT support, because the rule is defined as application controlled. That means the application is allowed to set the connection status as SSL. As long as the application does not set this status, it is not affected. However, the Policy Agent file allows also to restrict the application controlled SSL connections to particular ports, users or address spaces. The sample expects the certificate database on the HFS file / u/admin/CERT.kdb.
TTLSRule { LocalAddrSetRef RemoteAddrSetRef LocalPortRangeRef Direction Priority TTLSGroupActionRef TTLSEnvironmentActionRef TTLSConnectionActionRef } TTLSGroupAction { TTLSEnabled Trace } TTLSEnvironmentAction { HandshakeRole EnvironmentUserInstance TTLSKeyringParmsRef } TTLSConnectionAction { HandshakeRole TTLSCipherParmsRef TTLSConnectionAdvancedParmsRef Trace } TTLSConnectionAdvancedParms { ApplicationControlled } TTLSKeyringParms { Keyring KeyringStashFile } TTLSCipherParms { V3CipherSuites V3CipherSuites V3CipherSuites ConnRule01~1 addr1 addr1 portR1 Outbound 255 gAct1~AllUsersAsClient eAct1~AllUsersAsClient cAct1~AllUsersAsClient gAct1~AllUsersAsClient On 6 eAct1~AllUsersAsClient Client 0 keyR1 cAct1~AllUsersAsClient Client cipher1~AT-TLS__Silver cAdv1~AllUsersAsClient 0 cAdv1~AllUsersAsClient On keyR1 /u/admin/CERT.kdb /u/admin/CERT.sth cipher1~AT-TLS__Silver TLS_RSA_WITH_DES_CBC_SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_AES_128_CBC_SHA
Programming Guide
483
This message indicates a successful initialization. Check Policy-Agent job output JESMSGLG for:
EZZ8438I PAGENT POLICY DEFINITIONS CONTAIN ERRORS FOR <your TCP/IP address space>: TTLS
This message indicates errors in the configuration file. Check the syslog.log file for further information. Does the configuration rule cover the client? Check syslog.log for:
EZD1281I TTLS Map CONNID: 00002909 LOCAL: 10.20.91.61..1751 REMOTE: 10.20.91.117..443 JOBNAME: KSP USERID: KSP TYPE: OutBound STATUS: Appl Control RULE: ConnRule01 ACTIONS: gAct1 eAct1 AllUsersAsClient
The above entry indicates that the connection to Port 443 by user KSP is application controlled.
484
Programming Guide
Programming Guide
485
References
Below is a list of resources that you may find useful.
Training Courses
Software AG's Corporate University offers special training courses on this subject. See the Corporate University offerings on Empower at https://empower.softwareag.com/. Or, ask your local Software AG representative for the availability of special on-site training courses at your location.
Useful Links
Below is a collection of links that may be of interest.
World Wide Web Consortium (W3C): http://www.w3.org/ Extensible Markup Language (XML): http://www.w3.org/XML/ HyperText Markup Language (HTML) Home Page: http://www.w3.org/MarkUp/ W3 Schools: http://www.w3schools.com/
486
Programming Guide
56
The user interface of an application, that is, the way an application presents itself to the user, is a key consideration when writing an application. This part provides information on the various possibilities Natural offers for designing user interfaces that are uniform in presentation and provide powerful mechanisms for user guidance and interaction. When designing user interfaces, standards and standardization are key factors. Using Natural, you can offer the end user common functionality across various hardware and operating systems. This includes the general screen layout (information, data and message areas), function-key assignment and the layout of windows. This part covers the following topics:
Screen Design Dialog Design
487
488
57
Screen Design
Control of Function-Key Lines - Terminal Command %Y ........................................................................ 490 Control of the Message Line - Terminal Command %M .......................................................................... 494 Assigning Colors to Fields - Terminal Command %= ............................................................................. 497 Outlining - Terminal Command %D=B ................................................................................................ 498 Statistics Line/Infoline - Terminal Command %X ................................................................................... 498 Windows ...................................................................................................................................... 500 Standard/Dynamic Layout Maps ....................................................................................................... 509 Multilingual User Interfaces .............................................................................................................. 510 Skill-Sensitive User Interfaces .......................................................................................................... 515
489
Screen Design
%YS The function-key lines display the keys sequentially and only show those keys to which names have been assigned (PF1=value, PF2=value, etc.):
490
Programming Guide
Screen Design %YP The function-key lines are displayed in PC-like format, that is, sequentially and only showing those keys to which names have been assigned (F1=value, F2=value, etc.):
Other Display Options Various other command options are available for function-key lines, such as:
single- and double-line display, intensified display, reverse video display, color display.
For details on these options, see %Y - Control of PF-Key Lines in the Terminal Commands documentation.
Function _ _ _ _ _ _ _ _ Development Functions Development Environment Settings Maintenance and Transfer Utilities Debugging and Monitoring Utilities Example Libraries Other Products Help Exit Natural Session
Programming Guide
491
Screen Design
%YT The function-key lines are displayed at the top of the screen.
Enter-PF1---PF2---PF3---PF4---PF5---PF6---PF7---PF8---PF9---PF10--PF11--PF12--Help Exit Canc 16:50:53 ***** NATURAL ***** 2002-12-18 User SAG - Main Menu Library XYZ
Function
_ Development Functions _ Development Environment Settings _ Maintenance and Transfer Utilities _ Debugging and Monitoring Utilities _ Example Libraries _ Other Products _ Help _ Exit Natural Session
492
Programming Guide
Screen Design
Command ===>
%Ynn The function-key lines are displayed on line nn of the screen. In the example below the functionkey line has been set to line 10:
Function
_ Development Functions _ Development Environment Settings _ Maintenance and Transfer Utilities Enter-PF1---PF2---PF3---PF4---PF5---PF6---PF7---PF8---PF9---PF10--PF11--PF12--Help Exit - Debugging and Monitoring Utilities _ Example Libraries _ Other Products _ Help _ Exit Natural Session Canc
Programming Guide
493
Screen Design
Command ===>
Cursor-Sensitivity
%YC This command makes the function-key lines cursor-sensitive. This means that they act like an action bar on a PC screen: you just move the cursor to the desired function-key number or name and press Enter, and Natural reacts as if the corresponding function key had been pressed. To switch cursor-sensitivity off, you enter %YC again (toggle switch). By using %YC in conjunction with tabular display format (%YN) and having only the functionkey names displayed (%YH), you can equip your applications with very comfortable action bar processing: the user merely has to select a function name with the cursor and press Enter, and the function is executed.
Positioning the Message Line Message Line Protection Message Line Color
494
Programming Guide
Screen Design
Function
_ Development Functions _ Development Environment Settings _ Maintenance and Transfer Utilities _ Debugging and Monitoring Utilities _ Example Libraries _ Other Products _ Help _ Exit Natural Session
Programming Guide
495
Screen Design
Please enter a function. 16:50:53 User SAG ***** NATURAL ***** - Main Menu 2002-12-18 Library XYZ
Function
_ Development Functions _ Development Environment Settings _ Maintenance and Transfer Utilities _ Debugging and Monitoring Utilities _ Example Libraries _ Other Products _ Help _ Exit Natural Session
Command ===>
496
Programming Guide
Screen Design
Enter-PF1---PF2---PF3---PF4---PF5---PF6---PF7---PF8---PF9---PF10--PF11--PF12--Help Exit
Other options for the positioning of the message line are described in %M - Control of Message Line in the Terminal Commands documentation.
Programming Guide
497
Screen Design
Codes Description U V BG BL GR NE PI RE TU YE Underlined Reverse video Background Blue Green Neutral Pink Red Turquoise Yellow
Example:
%=TI=RE,OB=YE
This example assigns the color red to all intensified text fields and yellow to all blinking output fields.
Statistics Line
498
Programming Guide
Screen Design
Infoline
Statistics Line
To turn the statistics line on/off, enter the terminal command %X (this is a toggle function). If you set the statistics line on, you can see statistical information, such as:
the number of bytes transmitted to the screen during the previous screen operation, the logical line size of the current page, the physical line size of the window.
For full details regarding the statistics line, see the terminal command %X as described in the Terminal Commands documentation. The example below shows the statistics line displayed at the bottom of the screen:
> > + Program POS Lib SAG All ....+....1....+....2....+....3....+....4....+....5....+....6....+....7.. 0010 SET CONTROL 'XT' 0020 SET CONTROL 'XI+' 0030 DEFINE PRINTER (2) OUTPUT 'INFOLINE' 0040 WRITE (2) 'EXECUTING' *PROGRAM 'BY' *INIT-USER 0050 WRITE 'TEST OUTPUT' 0070 END 0080 0090 0100 0110 0120 0130 0140 0150 0160 0170 0180 0190 0200 IO=264,AI =292,L=0 C= ,LS=80,P =23,PLS=80,PCS=24,FLD=82,CLS=1,ADA=0
Programming Guide
499
Screen Design
Infoline
You can also use the statistics line as an infoline where status information can be displayed, for example, for debugging purposes, or you can use it as a separator line (as defined by SAA standards). To define the statistics line as an infoline, you use the terminal command %XI+. Once you have activated the infoline with the above command, you can define the infoline as the output destination for data with the DEFINE PRINTER statement as demonstrated in the example below:
SET CONTROL 'XT' SET CONTROL 'XI+' DEFINE PRINTER (2) OUTPUT 'INFOLINE' WRITE (2) 'EXECUTING' *PROGRAM 'BY' *INIT-USER WRITE 'TEST OUTPUT' END
When the above program is run, the status information is displayed in the infoline at the top of the output display:
For further details on the statistics line/infoline, see the terminal command %X as described in the Terminal Commands documentation.
Windows
Below is information on:
500
Programming Guide
Screen Design
What is a Window?
A window is that segment of a logical page, built by a program, which is displayed on the terminal screen. A logical page is the output area for Natural; in other words the logical page contains the current report/map produced by the Natural program for display. This logical page may be larger than the physical screen. There is always a window present, although you may not be aware of its existence. Unless specified differently (by a DEFINE WINDOW statement), the size of the window is identical to the physical size of your terminal screen. You can manipulate a window in two ways:
You can control the size and position of the window on the physical screen. You can control the position of the window on the logical page.
Positioning on the Physical Screen The figure below illustrates the positioning of a window on the physical screen. Note that the same section of the logical page is displayed in both cases, only the position of the window on the screen has changed.
Programming Guide
501
Screen Design
Positioning on the Logical Page The figure below illustrates the positioning of a window on the logical page. When you change the position of the window on the logical page, the size and position of the window on the physical screen will remain unchanged. In other words, the window is not moved over the page, but the page is moved underneath the window.
502
Programming Guide
Screen Design
** Example 'WINDX01': DEFINE WINDOW ************************************************************************ DEFINE DATA LOCAL 1 COMMAND (A10) END-DEFINE * DEFINE WINDOW TEST SIZE 5*25 BASE 5/40 TITLE 'Sample Window' CONTROL WINDOW
Programming Guide
503
Screen Design
FRAMED POSITION SYMBOL BOTTOM LEFT * INPUT WINDOW='TEST' WITH TEXT 'message line' COMMAND (AD=I'_') / 'dataline 1' / 'dataline 2' / 'dataline 3' 'long data line' * IF COMMAND = 'TEST2' FETCH 'WINDX02' ELSE IF COMMAND = '.' STOP ELSE REINPUT 'invalid command' END-IF END-IF END
The window-name identifies the window. The name may be up to 32 characters long. For a window name, the same naming conventions apply as for user-defined variables. Here the name is TEST. The window size is set with the SIZE option. Here the window is 5 lines high and 25 columns (positions) wide. The position of the window is set by the BASE option. Here the top left-hand corner of the window is positioned on line 5, column 40. With the TITLE option, you can define a title that is to be displayed in the window frame (of course, only if you have defined a frame for the window). With the CONTROL clause, you determine whether the PF-key lines, the message line and the statistics line are displayed in the window or on the full physical screen. Here CONTROL WINDOW causes the message line to be displayed inside the window. CONTROL SCREEN would cause the lines to be displayed on the full physical screen outside the window. If you omit the CONTROL clause, CONTROL WINDOW applies by default. With the FRAMED option, you define that the window is to be framed. This frame is then cursorsensitive. Where applicable, you can page forward, backward, left or right within the window by simply placing the cursor over the appropriate symbol (<, -, +, or >; see POSITION clause) and then pressing Enter. In other words, you are moving the logical page underneath the window on the physical screen. If no symbols are displayed, you can page backward and forward within the window by placing the cursor in the top frame line (for backward positioning) or bottom frame line (for forward positioning) and then pressing Enter. With the POSITION clause of the FRAMED option, you define that information on the position of the window on the logical page is to be displayed in the frame of the window. This applies only if the logical page is larger than the window; if it is not, the POSITION clause will be ignored. The position
504
Programming Guide
Screen Design information indicates in which directions the logical page extends above, below, to the left and to the right of the current window. If the POSITION clause is omitted, POSITION SYMBOL TOP RIGHT applies by default.
POSITION SYMBOL causes the position information to be displayed in form of symbols: More: < -
+ >. The information is displayed in the top and/or bottom frame line.
TOP/BOTTOM determines whether the position information is displayed in the top or bottom frame
line.
LEFT/RIGHT determines whether the position information is displayed in the left or right part of
the frame line. You can define which characters are to be used for the frame with the terminal command %F=chv.
c The first character will be used for the four corners of the window frame. h The second character will be used for the horizontal frame lines. v The third character will be used for the vertical frame lines.
Example:
%F=+-!
The above command makes the window frame look like this:
+------------------------+ ! ! ! ! ! ! ! ! +------------------------+
Programming Guide
505
Screen Design
> r Top 0010 0020 0030 0040 0050 0060 0070 0080 0090 0100 0110 0120 0130 0140 0150 0160 0170 0180 0190 0200 > + Program WINDX01 Lib SYSEXPG ....+....1....+....2....+....3....+....4....+....5....+....6....+....7.. ** Example 'WINDX01': DEFINE WINDOW ******************************* +----Sample Window-----+ *************** DEFINE DATA LOCAL ! message line ! 1 COMMAND (A10) ! COMMAND __________ ! END-DEFINE ! dataline 1 ! * +More: + >---------+ DEFINE WINDOW TEST SIZE 5*25 BASE 5/40 TITLE 'Sample Window' CONTROL WINDOW FRAMED POSITION SYMBOL BOTTOM LEFT * INPUT WINDOW='TEST' WITH TEXT 'message line' COMMAND (AD=I'_') / 'dataline 1' / 'dataline 2' / 'dataline 3' 'long data line' * IF COMMAND = 'TEST2' ....+....1....+....2....+....3....+....4....+....5....+... S 29 L 1
In the bottom frame line, the position information More: + > indicates that there is more information on the logical page than is displayed in the window. To see the information that is further down on the logical page, you place the cursor in the bottom frame line on the plus (+) sign and press Enter. The window is now moved downwards. Note that the text long data line does not fit in the window and is consequently not fully visible.
> r Top 0010 0020 0030 0040 0050 0060 0070 0080 0090 0100 0110 0120 0130 0140 0150
> + Program WINDX01 Lib SYSEXPG ....+....1....+....2....+....3....+....4....+....5....+....6....+....7.. ** Example 'WINDX01': DEFINE WINDOW ******************************* +----Sample Window-----+ *************** DEFINE DATA LOCAL ! message line ! 1 COMMAND (A10) ! dataline 3 long data ! END-DEFINE ! dataline 2 ! * +More: >---------+ DEFINE WINDOW TEST SIZE 5*25 BASE 5/40 TITLE 'Sample Window' CONTROL WINDOW FRAMED POSITION SYMBOL BOTTOM LEFT * INPUT WINDOW='TEST' WITH TEXT 'message line' COMMAND (AD=I'_') /
506
Programming Guide
Screen Design
0160 'dataline 1' / 0170 'dataline 2' / 0180 'dataline 3' 'long data line' 0190 * 0200 IF COMMAND = 'TEST2' ....+....1....+....2....+....3....+....4....+....5....+... S 29
L 1
To see this hidden information to the right, you place the cursor in the bottom frame line on the less-than symbol (>) and press Enter. The window is now moved to the right on the logical page and displays the previously invisible word line:
> r Top 0010 0020 0030 0040 0050 0060 0070 0080 0090 0100 0110 0120 0130 0140 0150 0160 0170 0180 0190 0200
> + Program WINDX01 Lib SYSEXPG ....+....1....+....2....+....3....+....4....+....5....+....6....+....7.. ** Example 'WINDX01': DEFINE WINDOW ******************************* +----Sample Window-----+ *************** DEFINE DATA LOCAL ! message line ! 1 COMMAND (A10) ! line ! <== END-DEFINE ! ! * +More: < ---------+ DEFINE WINDOW TEST SIZE 5*25 BASE 5/40 TITLE 'Sample Window' CONTROL WINDOW FRAMED POSITION SYMBOL BOTTOM LEFT * INPUT WINDOW='TEST' WITH TEXT 'message line' COMMAND (AD=I'_') / 'dataline 1' / 'dataline 2' / 'dataline 3' 'long data line' * IF COMMAND = 'TEST2' ....+....1....+....2....+....3....+....4....+....5....+... S 29 L 1
Multiple Windows You can, of course, open multiple windows. However, only one Natural window is active at any one time, that is, the most recent window. Any previous windows may still be visible on the screen, but are no longer active and are ignored by Natural. You may enter input only in the most recent window. If there is not enough space to enter input, the window size must be adjusted first.
Programming Guide
507
Screen Design When TEST2 is entered in the COMMAND field, the program WINDX02 is executed.
** Example 'WINDX02': DEFINE WINDOW ************************************************************************ DEFINE DATA LOCAL 1 COMMAND (A10) END-DEFINE * DEFINE WINDOW TEST2 SIZE 5*30 BASE 15/40 TITLE 'Another Window' CONTROL SCREEN FRAMED POSITION SYMBOL BOTTOM LEFT * INPUT WINDOW='TEST2' WITH TEXT 'message line' COMMAND (AD=I'_') / 'dataline 1' / 'dataline 2' / 'dataline 3' 'long data line' * IF COMMAND = 'TEST' FETCH 'WINDX01' ELSE IF COMMAND = '.' STOP ELSE REINPUT 'invalid command' END-IF END-IF END
A second window is opened. The other window is still visible, but it is inactive.
message line > r > + Program WINDX01 Lib SYSEXPG Top ....+....1....+....2....+....3....+....4....+....5....+....6....+....7.. 0010 ** Example 'WINDX01': DEFINE WINDOW 0020 ******************************* +----Sample Window-----+ *************** 0030 DEFINE DATA LOCAL ! message line ! Inactive 0040 1 COMMAND (A10) ! COMMAND TEST2_____ ! Window 0050 END-DEFINE ! dataline 1 ! <== 0060 * +More: + >---------+ 0070 DEFINE WINDOW TEST 0080 SIZE 5*25 0090 BASE 5/40 0100 TITLE 'Sample Window' 0110 CONTROL WINDOW 0120 FRAMED POSITION SYMBOL B +------Another Window-------+ Currently
508
Programming Guide
Screen Design
* ! COMMAND __________ ! INPUT WINDOW='TEST' WITH TEXT ' ! dataline 1 ! COMMAND (AD=I'_') / ! dataline 2 ! 'dataline 1' / +More: +------------------+ 'dataline 2' / 'dataline 3' 'long data line' * IF COMMAND = 'TEST2'
Note that for the new window the message line is now displayed on the full physical screen (at the top) and not in the window. This was defined by the CONTROL SCREEN clause in the WINDX02 program. For further details on the statements DEFINE WINDOW, INPUT WINDOW and SET WINDOW, see the corresponding descriptions in the Statements documentation.
Programming Guide
509
Screen Design
Define Map Settings for MAP Format --------------------------Page Size ...... 23 Line Size ...... 79 Column Shift ... 0 (0/1) Layout ......... STAN1___ dynamic ....... Y (Y/N) Zero Print ..... N (Y/N) Case Default ... UC (UC/LC) Manual Skip .... N (Y/N) Decimal Char ... . Standard Keys .. Y (Y/N) Justification .. L (L/R) Print Mode ..... __ Control Var .... ________
2001-01-22 Context -------------------------Device Check .... ________ WRITE Statement _ INPUT Statement X Help ____________________ as field default N (Y/N)
Automatic Rule Rank 1 Profile Name .... SYSPROF Filler Characters -----------------------Optional, Partial .... _ Required, Partial .... _ Optional, Complete ... _ Required, Complete ... _
N (Y/N)
For further details on layout maps, see Map Editor in the Editors documentation.
Language Codes Defining the Language of a Natural Object Defining the User Language Referencing Multilingual Objects Programs Error Messages
510
Programming Guide
Screen Design
Language Codes
In Natural, each language has a language code (from 1 to 60). The table below is an extract from the full table of language codes. For a complete overview, refer to the description of the system variable *LANGUAGE in the System Varibales documentation.
Language Code Language 1 2 3 4 5 6 7 8 9 10 11 English German French Spanish Italian Dutch Turkish Danish Albanian Map Code in Object Names 1 2 3 4 5 6 7 8 A
Norwegian 9 Portuguese B
The language code (left column) is the code that is contained in the system variable *LANGUAGE. This code is used by Natural internally. It is the code you use to define the user language (see Defining the User Language below). The code you use to identify the language of a Natural object is the map code in the right-hand column of the table. Example: The language code for Portuguese is 11. The code you use when cataloging a Portuguese Natural object is B. For the full table of language codes, see the system variable *LANGUAGE as described in the System Variables documentation.
Programming Guide
511
Screen Design
Defining Languages with Alphabetical Map Codes Map codes are in the range 1-9, A-Z or a-y. The alphabetical map codes require special handling. Normally, it is not possible to catalog an object with a lower-case letter in the name - all characters are automatically converted into capitals. This is however necessary, if for example you wish to define an object for Kanji (Japanese) which has the language code 59 and the map code x. To catalog such an object, you first set the correct language code (here 59) using the terminal command %L=nn, where nn is the language code. You then catalog the object using the ampersand (&) character instead of the actual map code in the object name. So to have a Japanese version of the map DEMO, you stow the map under the name DEMO&. If you now look at the list of Natural objects, you will see that the map is correctly listed as DEMOx. Objects with language codes 1-9 and upper case A-Z can be cataloged directly without the use of the ampersand (&) notation. In the example list below, you can see the three maps DEMO1, DEMO2 and DEMOx. To delete the map DEMOx, you use the same method as when creating it, that is, you set the correct language with the terminal command %L=59 and then confirm the deletion with the ampersand (&) notation (DEMO&).
512
Programming Guide
Screen Design
08:41:14 User SAG Cmd --__ __ __ __ __ __ __ de __ __ __ __ __ __ From ***** NATURAL LIST COMMAND ***** LIST * * 2001-01-25 Library SAG Date -------92-01-21 92-01-22 92-01-22 92-01-21 91-06-03 91-06-03 92-01-29 92-02-25 92-01-22 92-01-22 91-08-12 91-08-12 91-08-15 91-08-16 0 Time -------14:34:39 09:37:02 09:37:41 14:13:14 12:08:30 12:03:52 09:07:52 08:41:04 08:38:32 08:07:32 14:01:10 14:01:32 13:02:20 08:03:56
Name Type S/C SM Vers Level User-ID -------- ----------- --- -- ---- ----- -------COM3 Program S/C S 2.2 0002 SAG CUR Program +--------- DELETE ---------+ CURS Map ! ! D Program ! Please confirm deletion ! DARL Program ! with name DEMOx ! DARL1 Local ! DEMO&___ ! DAV Program +--------------------------+ DEMOx Map S/C S 2.2 0002 SAG DEMO1 Map S/C S 2.2 0002 SAG DEMO2 Map S/C S 2.2 0002 SAG DOWNCOM Program S S 2.2 0001 SAG DOWNCOMR Program S S 2.2 0001 SAG DOWNCOM2 Program S S 2.2 0001 SAG DOWNDIR Program S S 2.2 0001 SAG ________ (New start value)
DEFINE DATA LOCAL 1 PERSONNEL VIEW OF EMPLOYEES 2 NAME (A20) 2 PERSONNEL-ID (A8) 1 CAR VIEW OF VEHICLES 2 REG-NUM (A15) 1 #CODE (N1) END-DEFINE
Programming Guide
513
Screen Design
* INPUT USING MAP 'DEMO&' /* <--- INVOKE MAP WITH CURRENT LANGUAGE CODE ...
When this program is run, the English map (DEMO1) is displayed. This is because the current value of *LANGUAGE is 1 = English.
MAP DEMO1
SAMPLE MAP
In the example below, the language code has been switched to 2 = German with the terminal command %L=2. When the program is now run, the German map (DEMO2) is displayed.
BEISPIEL-MAP
514
Programming Guide
Screen Design
Programs
For some applications it may be useful to define multilingual programs. For example, a standard invoicing program, might use different subprograms to handle various tax aspects, depending on the country where the invoice is to be written. Multilingual programs are defined with the same technique as described above for maps.
Error Messages
Using the Natural utility SYSERR, you can translate Natural error messages into up to 60 languages, and also define your own error messages. Which message language a user sees, depends on the *LANGUAGE system variable. For further information on error messages, see SYSERR Utility in the Utilities documentation.
Programming Guide
515
Screen Design The following map (PERS1) includes instructions for the end user on how to select a function from the menu. The information is very detailed. The name of the map contains the map code 1:
_ _
To select a function, do one of the following: - place the cursor on the input field next to desired function and press Enter - mark the input field next to desired function with an X and press Enter - enter the desired function code (1 or 2) in the 'Enter code' field and press Enter
The same map, but without the detailed instructions is saved under the same name, but with map code 2.
MAP PERS2
_ _
In the example above, the map with the detailed instructions is output, if the ULANG profile parameter has the value 1, the map without the instructions if the value is 2. See also the description of the profile parameter ULANG (in the Parameter Reference).
516
Programming Guide
58
Dialog Design
Field-Sensitive Processing .............................................................................................................. 518 Simplifying Programming ................................................................................................................ 520 Line-Sensitive Processing ............................................................................................................... 521 Column-Sensitive Processing ........................................................................................................... 522 Processing Based on Function Keys .................................................................................................. 523 Processing Based on Function-Key Names ......................................................................................... 524 Processing Data Outside an Active Window ........................................................................................ 524 Copying Data from a Screen ............................................................................................................ 527 Statements REINPUT/REINPUT FULL .............................................................................................. 531 Object-Oriented Processing - The Natural Command Processor .............................................................. 532
517
Dialog Design This chapter tells you how you can design user interfaces that make user interaction with the application simple and flexible.
Field-Sensitive Processing
*CURS-FIELD and POS(field-name)
Using the system variable *CURS-FIELD together with the system function POS(field-name), you can define processing based on the field where the cursor is positioned at the time the user presses Enter.
*CURS-FIELD contains the internal identification of the field where the cursor is currently positioned;
it cannot be used by itself, but only in conjunction with POS(field-name). You can use *CURS-FIELD and POS(field-name), for example, to enable a user to select a function simply by placing the cursor on a specific field and pressing Enter. The example below illustrates such an application:
DEFINE DATA LOCAL 1 #EMP (A1) 1 #CAR (A1) 1 #CODE (N1) END-DEFINE * INPUT USING MAP 'CURS' * DECIDE FOR FIRST CONDITION WHEN *CURS-FIELD = POS(#EMP) OR #EMP = 'X' OR #CODE = 1 FETCH 'LISTEMP' WHEN *CURS-FIELD = POS(#CAR) OR #CAR = 'X' OR #CODE = 2 FETCH 'LISTCAR' WHEN NONE REINPUT 'PLEASE MAKE A VALID SELECTION' END-DECIDE END
518
Programming Guide
_ _
Enter code:
To select a function, do one of the following: - place the cursor on the input field next to desired function and press Enter - mark the input field next to desired function with an X and press Enter - enter the desired function code (1 or 2) in the 'Enter code' field and press Enter
If the user places the cursor on the input field (#EMP) next to Employee information, and presses Enter, the program LISTEMP displays a list of employee names:
Page
2001-01-22
09:39:32
NAME -------------------ABELLAN ACHIESON ADAM ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON AECKERLE AFANASSIEV AFANASSIEV AHL AKROYD
Notes: 1. In Natural for Ajax applications, *CURS-FIELD identifies the operand that represents the value of the control that has the input focus. You may use *CURS-FIELD in conjunction with the POS
Programming Guide
519
Dialog Design function to check for the control that has the input focus and perform processing depending on that condition. 2. The values of *CURS-FIELD and POS(field-name) serve for internal identification of the fields only. They cannot be used for arithmetical operations.
Simplifying Programming
System Function POS
The Natural system function POS(field-name) contains the internal identification of the field whose name is specified with the system function.
POS(field-name) may be used to identify a specific field, regardless of its position in a map. This
means that the sequence and number of fields in a map may be changed, but POS(field-name) will still uniquely identify the same field. With this, for example, you need only a single REINPUT statement to make the field to be MARKed dependent on the program logic. Note: The value POS(field-name) serves for internal identification of the fields only. It cannot be used for arithmetical operations. Example:
... DECIDE ON FIRST VALUE OF ... VALUE ... COMPUTE #FIELDX = POS(FIELD1) VALUE ... COMPUTE #FIELDX = POS(FIELD2) ... END-DECIDE ... REINPUT ... MARK #FIELDX ...
Full details on *CURS-FIELD and POS(field-name) are described in the System Variables and System Functions documention.
520
Programming Guide
Dialog Design
Line-Sensitive Processing
System Variable *CURS-LINE
Using the system variable *CURS-LINE, you can make processing dependent on the line where the cursor is positioned at the time the user presses Enter. Using this variable, you can make user-friendly menus. With the appropriate programming, the user merely has to place the cursor on the line of the desired menu option and press Enter to execute the option. The cursor position is defined within the current active window, regardless of its physical placement on the screen. Note: The message line, function-key lines and statistics line/infoline are not counted as data lines on the screen. The example below demonstrates line-sensitive processing using the *CURS-LINE system variable. When the user presses Enter on the map, the program checks if the cursor is positioned on line 8 of the screen which contains the option Employee information. If this is the case, the program that lists the names of employees LISTEMP is executed.
DEFINE DATA LOCAL 1 #EMP (A1) 1 #CAR (A1) 1 #CODE (N1) END-DEFINE * INPUT USING MAP 'CURS' * DECIDE FOR FIRST CONDITION WHEN *CURS-LINE = 8 FETCH 'LISTEMP' WHEN NONE REINPUT 'PLACE CURSOR ON LINE OF OPTION YOU WISH TO SELECT' END-DECIDE END
Programming Guide
521
Place the cursor on the line of the option you wish to select and press Enter
The user places the cursor indicated by square brackets [] on the line of the desired option and presses Enter and the corresponding program is executed.
Column-Sensitive Processing
System Variable *CURS-COL
The system variable *CURS-COL can be used in a similar way to *CURS-LINE described above. With *CURS-COL you can make processing dependent on the column where the cursor is positioned on the screen.
522
Programming Guide
Dialog Design
... SET KEY PF1 * INPUT USING MAP 'DEMO&' IF *PF-KEY = 'PF1' WRITE 'Help is currently not active' END-IF ...
The SET KEY statement activates PF1 as a function key. The IF statement defines what action is to be taken when the user presses PF1. The system variable *PF-KEY is checked for its current content; if it contains PF1, the corresponding action is taken. Further details regarding the statement SET KEY and the system variable *PF-KEY are described in the Statements and the System Variables documentation respectively.
Programming Guide
523
Dialog Design
... SET KEY PF3 NAMED 'INFO' PF12 NAMED 'INFO' INPUT USING MAP 'DEMO&' IF *PF-NAME = 'INFO' WRITE 'Help is currently not active' END-IF ...
The function names defined with NAMED appear in the function-key lines:
Enter-PF1---PF2---PF3---PF4---PF5---PF6---PF7---PF8---PF9---PF10--PF11--PF12--INFO INFO
524
Programming Guide
Dialog Design
DEFINE DATA LOCAL 1 #VALUE1 (N4) 1 #VALUE2 (N4) 1 #SUM3 (N8) END-DEFINE * DEFINE WINDOW EMP SIZE 8*17 BASE 10/2 TITLE 'Total of Add' CONTROL SCREEN FRAMED POSITION SYMBOL BOT LEFT * INPUT USING MAP 'WINDOW' * COMPUTE #SUM3 = #VALUE1 + #VALUE2 *
Programming Guide
525
Dialog Design
SET WINDOW 'EMP' INPUT (AD=O) / 'Value 1 +' / 'Value 2 =' // ' ' #SUM3 * IF *COM = 'M' FETCH 'MULTIPLY' #VALUE1 #VALUE2 END-IF END
Map to Demonstrate Windows with *COM CALCULATOR Enter values you wish to calculate
12__ 12__
Next line is input field (*COM) for input outside the window:
In this example, by entering the value M, the user initiates a multiplication function; the two values from the input map are multiplied and the result is displayed in a second window:
Map to Demonstrate Windows with *COM CALCULATOR Enter values you wish to calculate
526
Programming Guide
Dialog Design
! Value 2 = ! ! ! ! 24 ! ! ! +--------------+ ! Value 2 = ! ! ! ! 144 ! ! ! +--------------+
Next line is input field (*COM) for input outside the window: M
Programming Guide
527
Dialog Design
DEFINE DATA LOCAL 1 EMP VIEW OF EMPLOYEES 2 NAME(A20) 2 MIDDLE-NAME (A20) 2 PERSONNEL-ID (A8) END-DEFINE * READ EMP BY NAME STARTING FROM 'ABELLAN' THRU 'ALESTIA' DISPLAY NAME END-READ FETCH 'COM2' END
Page
2006-08-12
09:41:21
528
Programming Guide
Dialog Design
ADKINSON ADKINSON ADKINSON ADKINSON AECKERLE AFANASSIEV AFANASSIEV AHL AKROYD ALEMAN ALESTIA MORE
DEFINE DATA LOCAL 1 EMP VIEW OF EMPLOYEES 2 NAME(A20) 2 MIDDLE-NAME (A20) 2 PERSONNEL-ID (A8) 1 SELECTNAME (A20) END-DEFINE * SET KEY PF5 = '%CCC' * INPUT NO ERASE 'SELECT FIELD WITH CURSOR AND PRESS PF5' * MOVE *COM TO SELECTNAME FIND EMP WITH NAME = SELECTNAME DISPLAY NAME PERSONNEL-ID END-FIND END
In this program, the terminal command %CCC is assigned to PF5. The terminal command copies all protected data from the line where the cursor is positioned to the system variable *COM. This information is then available for further processing. This further processing is defined in the program lines shown in boldface.
Programming Guide
529
Dialog Design The user can now position the cursor on the name that interests him; when he/she now presses PF5, further employee information is supplied.
2006-08-12
09:44:25
ABELLAN ACHIESON ADAM <== Cursor positioned on name for which more information is required ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON ADKINSON AECKERLE AFANASSIEV AFANASSIEV AHL AKROYD ALEMAN ALESTIA
Page
1 NAME
2006-08-12
09:44:52
530
Programming Guide
Dialog Design
With an ordinary REINPUT statement (without FULL option), the contents of variables that were changed between the INPUT and REINPUT statement will not be displayed; that is, all variables on the screen will show the contents they had when the INPUT statement was originally executed. With a REINPUT FULL statement, all changes that have been made after the initial execution of the INPUT statement will be applied to the INPUT statement when it is re-executed; that is, all variables on the screen contain the values they had when the REINPUT statement was executed. If you wish to position the cursor to a specified field, you can use the MARK option, and to position to a particular position within a specified field, you use the MARK POSITION option.
The example below illustrates the use of REINPUT FULL with MARK POSITION.
DEFINE DATA LOCAL 1 #A (A10) 1 #B (N4) 1 #C (N4) END-DEFINE * INPUT (AD=M) #A #B #C IF #A = ' ' COMPUTE #B = #B + #C RESET #C REINPUT FULL 'Enter a value' MARK POSITION 5 IN *#A END-IF END
Programming Guide
531
Dialog Design The user enters 3 in field #B and 3 in field #C and presses Enter.
#A
#B
3 #C
The program requires field #A to be non-blank. The REINPUT FULL statement with MARK POSITION 5 IN *#A returns the input screen; the now modified variable #B contains the value 6 (after the COMPUTE calculation has been performed). The cursor is positioned to the 5th position in field #A ready for new input.
6 #C
Enter a value
This is the screen that would be returned by the same statement, without the FULL option. Note that the variables #B and #C have been reset to their status at the time of execution of the INPUT statement (each field contains the value 3).
#A
#B
3 #C
The development part is the utility SYSNCP. With this utility, you define commands and the actions to be performed in response to the execution of these commands. From your definitions, SYSNCP generates decision tables which determine what happens when a user enters a command. The run-time part is the statement PROCESS COMMAND. This statement is used to invoke the Command Processor within a Natural program. In the statement you specify the name of the SYSNCP table to be used to handle the data input by a user at that point.
For further information regarding the Natural Command Processor, see SYSNCP Utility in the Utilities documentation and the statement PROCESS COMMAND as described in the Statements documentation.
532
Programming Guide
59
NaturalX
This part describes how to develop object-based applications. The following topics are covered:
Introduction to NaturalX Developing NaturalX Applications
533
534
60
Introduction to NaturalX
535
Introduction to NaturalX This chapter contains a short introduction to component-based programming involving the use of the NaturalX interface and a dedicated set of Natural statements.
Why NaturalX?
Software applications that are based on component architecture offer many advantages over traditional designs. These include the following:
Faster development. Programmers can build applications faster by assembling software from prebuilt components. Reduced development costs. Having a common set of interfaces for programs means less work integrating the components into complete solutions. Improved flexibility. It is easier to customize software for different departments within a company by just changing some of the components that constitute the application. Reduced maintenance costs. In the case of an upgrade, it is often sufficient to change some of the components instead of having to modify the entire application.
Using NaturalX you can create component-based applications. You can use NaturalX to apply a component-based programming style. However, on this platform the components cannot be distributed and can only run in a local Natural session.
536
Programming Guide
61
Development Environments ............................................................................................................. 538 Defining Classes ........................................................................................................................... 538 Using Classes and Objects .............................................................................................................. 543
537
Developing NaturalX Applications This chapter describes how to develop an application by defining and using classes.
Development Environments
Developing Classes on Windows Platforms On Windows platforms, Natural provides the Class Builder as the tool to develop Natural classes. The Class Builder shows a Natural class in a structured hierarchical order and allows the user to manage the class and its components efficiently. If you use the Class Builder, no knowledge or only a basic knowledge of the syntax elements described below is required. Developing Classes Using SPoD In a Natural Single Point of Development (SPoD) environment that includes a Mainframe, UNIX and/or OpenVMS remote development server, you can use the Class Builder available with the Natural Studio front-end to develop classes on Mainframe, UNIX and/or OpenVMS platforms. In this case, no knowledge or only a basic knowledge of the syntax elements described below is required. Developing Classes on Mainframe, UNIX or OpenVMS Platforms If you do not use SPoD, you develop classes on these platforms using the Natural program editor. In this case, you should know the syntax of class definition described below.
Defining Classes
When you define a class, you must create a Natural class module, within which you create a DEFINE CLASS statement. Using the DEFINE CLASS statement, you assign the class an externally usable name and define its interfaces, methods and properties. You can also assign an object data area to the class, which describes the layout of an instance of the class. This section covers the following topics:
Creating a Natural Class Module Specifying a Class Defining an Interface Assigning an Object Data Variable to a Property Assigning a Subprogram to a Method
538
Programming Guide
Implementing Methods
Use the CREATE OBJECT statement to create a Natural object of type Class.
Specifying a Class
The DEFINE CLASS statement defines the name of the class, the interfaces the class supports and the structure of its objects. To specify a class
Defining an Interface
Each interface of a class is specified with an INTERFACE statement inside the class definition. An INTERFACE statement specifies the name of the interface and a number of properties and methods. For classes that are to be registered as COM classes, it specifies also the globally inique ID of the interface. A class can have one or several interfaces. For each interface, one INTERFACE statement is coded in the class definition. Each INTERFACE statement contains one or several PROPERTY and METHOD clauses. Usually the properties and methods contained in one interface are related from either a technical or a business point of view. The PROPERTY clause defines the name of a property and assigns a variable from the object data area to the property. This variable is used to store the value of the property. The METHOD clause defines the name of a method and assigns a subprogram to the method. This subprogram is used to implement the method. To define an interface
Programming Guide
539
Implementing Methods
A method is implemented as a Natural subprogram in the following general form:
For information on the DEFINE DATA statement see the Statements documentation. All clauses of the DEFINE DATA statement are optional. It is recommended that you use data areas instead of inline data definitions to ensure data consistency. If a PARAMETER clause is specified, the method can have parameters and/or a return value.
540
Programming Guide
Developing NaturalX Applications Parameters that are marked BY VALUE in the parameter data area are input parameters of the method. Parameters that are not marked BY VALUE are passed by reference and are input/output parameters. This is the default. The first parameter that is marked BY VALUE RESULT is returned as the return value for the method. If more than one parameter is marked in this way, the others will be treated as input/output parameters. Parameters that are marked OPTIONAL are available with Natural Version 4.1 and all subsequent releases. Optional parameters need not be specified when the method is called. They can be left unspecified by using the nX notation in the SEND METHOD statement. To make sure that the method subprogram accepts exactly the same parameters as specified in the corresponding METHOD statement in the class definition, use a parameter data area instead of inline data definitions. Use the same parameter data area as in the corresponding METHOD statement. To give the method subprogram access to the object data structure, the OBJECT clause can be specified. To make sure that the method subprogram can access the object data correctly, use a local data area instead of inline data definitions. Use the same local data area as specified in the OBJECT clause of the DEFINE CLASS statement. The GLOBAL, LOCAL and INDEPENDENT clauses can be used as in any other Natural program. While technically possible, it is usually not meaningful to use a CONTEXT clause in a method subprogram. The following example retrieves data about a given person from a table. The search key is passed as a BY VALUE parameter. The resulting data is returned through by reference parameters (by reference is the default definition). The return value of the method is defined by the specification BY VALUE RESULT.
Programming Guide
541
542
Programming Guide
Defining Object Handles Creating an Instance of a Class Invoking a Particular Method of an Object Accessing Properties
...
END-DEFINE
Example:
DEFINE DATA LOCAL 1 #MYOBJ1 HANDLE OF OBJECT 1 #MYOBJ2 (1:5) HANDLE OF OBJECT END-DEFINE
Programming Guide
543
Accessing Properties
Properties can be accessed using the ASSIGN (or COMPUTE ) statement as follows:
ASSIGN operand1.property-name = operand2 ASSIGN operand2 = operand1.property-name
As operand2, you specify an operand whose format must be data transfer-compatible to the format of the property. Please refer to the data transfer compatibility rules for further information.
property-name
The name of a property of the object. If the property name conforms to Natural identifier syntax, it can be specified as follows
544
Programming Guide
Developing NaturalX Applications If the property name does not conform to Natural identifier syntax, it must be enclosed in angle brackets:
The property name can also be qualified with an interface name. This is necessary if the object has more than one interface containing a property with the same name. In this case, the qualified property name must be enclosed in angle brackets:
Example:
define data local 1 #i (i2) 1 #o handle of object 1 #p (5) handle of object 1 #q (5) handle of object 1 #salary (p7.2) 1 #history (p7.2/1:10) end-define * ... * Code omitted for brevity. * ... * Set/Read the Salary property of the object #o. #o.Salary := #salary #salary := #o.Salary * Set/Read the Salary property of * the second object of the array #p. #p.Salary(2) := #salary #salary := #p.Salary(2) * * Set/Read the SalaryHistory property of the object #o. #o.SalaryHistory := #history(1:10) #history(1:10) := #o.SalaryHistory * Set/Read the SalaryHistory property of * the second object of the array #p. #p.SalaryHistory(2) := #history(1:10) #history(1:10) := #p.SalaryHistory(2) * * Set the Salary property of each object in #p to the same value. #p.Salary(*) := #salary * Set the SalaryHistory property of each object in #p
Programming Guide
545
In order to use arrays of object handles and properties that have arrays as values correctly, it is important to know the following: A property of an occurrence of an array of object handles is addressed with the following index notation:
#p.Salary(2) := #salary
A property that has an array as value is always accessed as a whole. Therefore no index notation is necessary with the property name:
#o.SalaryHistory := #history(1:10)
A property of an occurrence of an array of object handles which has an array as value is therefore addressed as follows:
#p.SalaryHistory(2) := #history(1:10)
546
Programming Guide
62
Alphabetical List of Natural Reserved Keywords .................................................................................. 548 Performing a Check for Natural Reserved Keywords ............................................................................. 563
547
Natural Reserved Keywords This chapter contains a list of all keywords that are reserved in the Natural programming language. Important: To avoid any naming conflicts, you are strongly recommended not to use Natural reserved keywords as names for variables.
548
Programming Guide
Natural Reserved Keywords AUTHORIZATION AUTO AVER AVG -BBACKOUT BACKWARD BASE BEFORE BETWEEN BLOCK BOT BOTTOM BREAK BROWSE BUT BX BY -CCABINET CALL CALLDBPROC CALLING CALLNAT CAP CAPTIONED CASE CC CD CDID CF CHAR CHARLENGTH CHARPOSITION CHILD CIPH CIPHER CLASS CLOSE CLR COALESCE CODEPAGE
Programming Guide
549
Natural Reserved Keywords COMMAND COMMIT COMPOSE COMPRESS COMPUTE CONCAT CONDITION CONST CONSTANT CONTEXT CONTROL CONVERSATION COPIES COPY COS COUNT COUPLED CS CURRENT CURSOR CV -DDATA DATAAREA DATE DAY DAYS DC DECIDE DECIMAL DEFINE DEFINITION DELETE DELIMITED DELIMITER DELIMITERS DESC DESCENDING DIALOG DIALOG-ID DIGITS DIRECTION DISABLED
550
Programming Guide
Natural Reserved Keywords DISP DISPLAY DISTINCT DIVIDE DL DLOGOFF DLOGON DNATIVE DNRET DO DOCUMENT DOEND DOWNLOAD DU DY DYNAMIC -EEDITED EJ EJECT ELSE EM ENCODED END END-ALL END-BEFORE END-BREAK END-BROWSE END-CLASS END-DECIDE END-DEFINE END-ENDDATA END-ENDFILE END-ENDPAGE END-ERROR END-FILE END-FIND END-FOR END-FUNCTION END-HISTOGRAM ENDHOC END-IF END-INTERFACE
Programming Guide
551
Natural Reserved Keywords END-LOOP END-METHOD END-NOREC END-PARAMETERS END-PARSE END-PROCESS END-PROPERTY END-PROTOTYPE END-READ END-REPEAT END-RESULT END-SELECT END-SORT END-START END-SUBROUTINE END-TOPPAGE END-WORK ENDING ENTER ENTIRE ENTR EQ EQUAL ERASE ERROR ERRORS ES ESCAPE EVEN EVENT EVERY EXAMINE EXCEPT EXISTS EXIT EXP EXPAND EXPORT EXTERNAL EXTRACTING -FFALSE FC
552
Programming Guide
Natural Reserved Keywords FETCH FIELD FIELDS FILE FILL FILLER FINAL FIND FIRST FL FLOAT FOR FORM FORMAT FORMATTED FORMATTING FORMS FORWARD FOUND FRAC FRAMED FROM FS FULL FUNCTION FUNCTIONS -GGC GE GEN GENERATED GET GFID GIVE GIVING GLOBAL GLOBALS GREATER GT GUI -HHANDLE
Programming Guide
553
Natural Reserved Keywords HAVING HC HD HE HEADER HEX HISTOGRAM HOLD HORIZ HORIZONTALLY HOUR HOURS HW -IIA IC ID IDENTICAL IF IGNORE IM IMMEDIATE IMPORT IN INC INCCONT INCDIC INCDIR INCLUDE INCLUDED INCLUDING INCMAC INDEPENDENT INDEX INDEXED INDICATOR INIT INITIAL INNER INPUT INSENSITIVE INSERT INT
554
Programming Guide
Natural Reserved Keywords INTEGER INTERCEPTED INTERFACE INTERFACE4 INTERMEDIATE INTERSECT INTO INVERTED INVESTIGATE IP IS ISN -JJOIN JUST JUSTIFIED -KKD KEEP KEY KEYS -LLANGUAGE LAST LC LE LEAVE LEAVING LEFT LENGTH LESS LEVEL LIB LIBPW LIBRARY LIBRARY-PASSWORD LIKE LIMIT LINDICATOR LINES
Programming Guide
555
Natural Reserved Keywords LISTED LOCAL LOCKS LOG LOG-LS LOG-PS LOGICAL LOOP LOWER LS LT -MMACROAREA MAP MARK MASK MAX MC MCG MESSAGES METHOD MGID MICROSECOND MIN MINUTE MODAL MODIFIED MODULE MONTH MORE MOVE MOVING MP MS MT MULTI-FETCH MULTIPLY -NNAME NAMED NAMESPACE NATIVE
556
Programming Guide
Natural Reserved Keywords NAVER NC NCOUNT NE NEWPAGE NL NMIN NO NODE NOHDR NONE NORMALIZE NORMALIZED NOT NOTIT NOTITLE NULL NULL-HANDLE NUMBER NUMERIC -OOBJECT OBTAIN OCCURRENCES OF OFF OFFSET OLD ON ONCE ONLY OPEN OPTIMIZE OPTIONAL OPTIONS OR ORDER OUTER OUTPUT -PPACKAGESET PAGE
Programming Guide
557
Natural Reserved Keywords PARAMETER PARAMETERS PARENT PARSE PASS PASSW PASSWORD PATH PATTERN PA1 PA2 PA3 PC PD PEN PERFORM PFn (n = 1 to 9) PFnn(nn = 10 to 99) PGDN PGUP PGM PHYSICAL PM POLICY POS POSITION PREFIX PRINT PRINTER PROCESS PROCESSING PROFILE PROGRAM PROPERTY PROTOTYPE PRTY PS PT PW -QQUARTER QUERYNO
558
Programming Guide
Natural Reserved Keywords -RRD READ READONLY REC RECORD RECORDS RECURSIVELY REDEFINE REDUCE REFERENCED REFERENCING REINPUT REJECT REL RELATION RELATIONSHIP RELEASE REMAINDER REPEAT REPLACE REPORT REPORTER REPOSITION REQUEST REQUIRED RESET RESETTING RESIZE RESPONSE RESTORE RESULT RET RETAIN RETAINED RETRY RETURN RETURNS REVERSED RG RIGHT ROLLBACK ROUNDED ROUTINE
Programming Guide
559
Natural Reserved Keywords ROW ROWS RR RS RULEVAR RUN -SSA SAME SCAN SCREEN SCROLL SECOND SELECT SELECTION SEND SENSITIVE SEPARATE SEQUENCE SERVER SET SETS SETTIME SF SG SGN SHORT SHOW SIN SINGLE SIZE SKIP SL SM SOME SORT SORTED SORTKEY SOUND SPACE SPECIFIED SQL SQLID
560
Programming Guide
Natural Reserved Keywords SQRT STACK START STARTING STATEMENT STATIC STATUS STEP STOP STORE SUBPROGRAM SUBPROGRAMS SUBROUTINE SUBSTR SUBSTRING SUBTRACT SUM SUPPRESS SUPPRESSED SUSPEND SYMBOL SYNC SYSTEM -TTAN TC TERMINATE TEXT TEXTAREA TEXTVARIABLE THAN THEM THEN THRU TIME TIMESTAMP TIMEZONE TITLE TO TOP TOTAL TP TR
Programming Guide
561
Natural Reserved Keywords TRAILER TRANSACTION TRANSFER TRANSLATE TREQ TRUE TS TYPE TYPES -UUC UNDERLINED UNION UNIQUE UNKNOWN UNTIL UPDATE UPLOAD UPPER UR USED USER USING -VVAL VALUE VALUES VARGRAPHIC VARIABLE VARIABLES VERT VERTICALLY VIA VIEW -WWH WHEN WHERE WHILE WINDOW
562
Programming Guide
Natural Reserved Keywords WITH WORK WRITE WITH_CTE -XXML -YYEAR -ZZD ZP
DEFINE DATA LOCAL 1 ADD (A10) END-DEFINE CALLNAT 'MYSUB' ADD 4 END
To check variable names in a programming object against such Natural reserved keywords, you can use one of the following facilities:
the KCHECK keyword subparameter of the CMPO profile parameter or NTCMPO parameter macro, or the KCHECK option of the COMPOPT system command.
Programming Guide
563
Natural Reserved Keywords The following table contains a list of Natural reserved keywords that are checked by KCHECK.
A-D A-AVER ABS ACCEPT ADD ALL A-MAX A-MIN A-NAVER A-NCOUNT A-NMIN ANY ASSIGN A-SUM AT ATN AVER BACKOUT BEFORE BREAK BROWSE CALL CALLDBPROC CALLNAT CLOSE COMMIT COMPOSE COMPRESS COMPUTE COPY COS COUNT CREATE DECIDE DEFINE DELETE DISPLAY DIVIDE DLOGOFF DLOGON DNATIVE DO DOEND DOWNLOAD E-F EJECT ELSE END END-ALL END-BEFORE END-BREAK END-BROWSE END-DECIDE END-ENDDATA END-DECIDE END-ENDDATA END-ENDFILE END-ENDPAGE END-ERROR END-FILE END-FIND END-FOR END-HISTOGRAM ENDHOC END-IF END-LOOP END-NOREC END-PARSE END-PROCESS END-READ END-REPEAT END-RESULT END-SELECT END-SORT END-START END-SUBROUTINE END-TOPPAGE END-WORK ENTIRE ESCAPE EXAMINE EXP EXPAND EXPORT FALSE FETCH FIND FOR FORMAT FRAC G-P GET HISTOGRAM IF IGNORE IMPORT INCCONT INCDIC INCDIR INCLUDE INCMAC INPUT INSERT INT INVESTIGATE LIMIT LOG LOOP MAP MAX MIN MOVE MULTIPLY NAVER NCOUNT NEWPAGE NMIN NONE NULL-HANDLE OBTAIN OLD ON OPEN OPTIONS PARSE PASSW PERFORM POS PRINT PROCESS R-S READ REDEFINE REDUCE REINPUT REJECT RELEASE REPEAT REQUEST RESET RESIZE RESTORE RET RETRY RETURN ROLLBACK RULEVAR RUN SELECT SEND SEPARATE SET SETTIME SGN SHOW SIN SKIP SORT SORTKEY SQRT STACK START STOP STORE SUBSTR SUBSTRING SUBTRACT SUM SUSPEND T-W TAN TERMINATE TOP TOTAL TRANSFER TRUE UNTIL UPDATE UPLOAD VAL VALUE VALUES WASTE WHEN WHILE WITH_CTE WRITE
564
Programming Guide
Programming Guide
565
566
63
READ Statement ........................................................................................................................... 568 FIND Statement ............................................................................................................................ 569 Nested READ and FIND Statements ................................................................................................. 573 ACCEPT and REJECT Statements ................................................................................................... 575 AT START OF DATA and AT END OF DATA Statements ........................................................................ 577 DISPLAY and WRITE Statements ..................................................................................................... 580 DISPLAY Statement ....................................................................................................................... 584 Column Headers ........................................................................................................................... 585 Field-Output-Relevant Parameters .................................................................................................... 587 Edit Masks ................................................................................................................................... 593 DISPLAY VERT with WRITE Statement ............................................................................................. 596 AT BREAK Statement ..................................................................................................................... 597 COMPUTE, MOVE and COMPRESS Statements ................................................................................ 598 System Variables ........................................................................................................................... 601 System Functions .......................................................................................................................... 604
567
Referenced Example Programs This chapter contains some additional example programs that are referenced in the Programming Guide.
READ Statement
The following example is referenced in the section Statements for Database Access. READX03 - READ statement (with LOGICAL clause)
** Example 'READX03': READ (with LOGICAL clause) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 PERSONNEL-ID 2 JOB-TITLE END-DEFINE * LIMIT 8 READ EMPLOY-VIEW LOGICAL BY PERSONNEL-ID DISPLAY NOTITLE *ISN NAME 'PERS-NO' PERSONNEL-ID 'POSITION' JOB-TITLE END-READ END
ISN NAME PERS-NO POSITION ----------- -------------------- -------- ------------------------204 205 206 207 208 209 210 211 SCHINDLER SCHIRM SCHMITT SCHMIDT SCHNEIDER SCHNEIDER BUNGERT THIELE 11100102 11100105 11100106 11100107 11100108 11100109 11100110 11100111 PROGRAMMIERER SYSTEMPROGRAMMIERER OPERATOR SEKRETAERIN SACHBEARBEITER SEKRETAERIN SYSTEMPROGRAMMIERER SEKRETAERIN
568
Programming Guide
FIND Statement
The following examples are referenced in the section Statements for Database Access. FINDX07 - FIND statement (with several clauses)
** Example 'FINDX07': FIND (with several clauses) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 SALARY (1) 2 CURR-CODE (1) END-DEFINE * FIND EMPLOY-VIEW WITH PHONETIC-NAME = 'JONES' OR = 'BECKR' AND CITY = 'BOSTON' THRU 'NEW YORK' BUT NOT 'CHAPEL HILL' SORTED BY NAME WHERE SALARY (1) < 28000 DISPLAY NOTITLE NAME FIRST-NAME CITY SALARY (1) END-FIND END
ANNUAL SALARY -------------------- -------------------- -------------------- ---------BAKER JONES JONES PAULINE MARTHA KEVIN DERBY KALAMAZOO DERBY 4450 21000 7000
NAME
FIRST-NAME
CITY
** Example 'FINDX08': FIND (with LIMIT) ** Demonstrates FIND statement with LIMIT option to ** terminate program with an error message if the ** number of records selected exceeds a specified ** limit (no output). ************************************************************************ DEFINE DATA LOCAL
Programming Guide
569
** Example 'FINDX09': FIND (using *NUMBER, *COUNTER, *ISN) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 DEPT 2 NAME END-DEFINE * FIND EMPLOY-VIEW WITH CITY = 'BOSTON' WHERE DEPT = 'TECH00' THRU 'TECH10' DISPLAY NOTITLE 'COUNTER' *COUNTER NAME DEPT 'ISN' *ISN AT START OF DATA WRITE '(TOTAL NUMBER IN BOSTON:' *NUMBER ')' / END-START END-FIND END
DEPARTMENT ISN CODE ----------- -------------------- ---------- ----------(TOTAL NUMBER IN BOSTON: 1 STANWOOD 2 PERREAULT 7 ) TECH10 TECH10 782 842
COUNTER
NAME
570
Programming Guide
** Example 'FINDX10': FIND (combined with READ) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 FIRST-NAME 1 VEHIC-VIEW VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 15 * EMP. READ EMPLOY-VIEW BY NAME STARTING FROM 'JONES' VEH. FIND VEHIC-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (EMP.) IF NO RECORDS FOUND MOVE '*** NO CAR ***' TO MAKE END-NOREC DISPLAY NOTITLE NAME (EMP.) (IS=ON) FIRST-NAME (EMP.) (IS=ON) MAKE (VEH.) END-FIND END-READ END
NAME FIRST-NAME MAKE -------------------- -------------------- -------------------JONES VIRGINIA MARSHA ROBERT LILLY EDWARD MARTHA LAUREL KEVIN GREGORY MANFRED DANIEL GABRIEL ERNST CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD MG GENERAL MOTORS GENERAL MOTORS GENERAL MOTORS DATSUN FORD *** NO CAR *** RENAULT *** NO CAR *** *** NO CAR ***
Programming Guide
571
** Example 'FINDX11': FIND NUMBER (with *NUMBER) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 FIRST-NAME 2 NAME 2 CITY 2 JOB-TITLE 2 SALARY (1) * 1 #PERCENT (N.2) 1 REDEFINE #PERCENT 2 #WHOLE-NBR (N2) 1 #ALL-BOST (N3.2) 1 #SECR-ONLY (N3.2) 1 #BOST-NBR (N3) 1 #SECR-NBR (N3) END-DEFINE * F1. FIND NUMBER EMPLOY-VIEW WITH CITY = 'BOSTON' F2. FIND NUMBER EMPLOY-VIEW WITH CITY = 'BOSTON' AND JOB-TITLE = 'SECRETARY' * MOVE *NUMBER(F1.) TO #ALL-BOST #BOST-NBR MOVE *NUMBER(F2.) TO #SECR-ONLY #SECR-NBR DIVIDE #ALL-BOST INTO #SECR-ONLY GIVING #PERCENT * WRITE TITLE LEFT JUSTIFIED UNDERLINED 'There are' #BOST-NBR 'employees in the Boston offices.' / #SECR-NBR '(=' #WHOLE-NBR (EM=99%')') 'are secretaries.' * SKIP 1 FIND EMPLOY-VIEW WITH CITY = 'BOSTON' AND JOB-TITLE = 'SECRETARY' DISPLAY NAME FIRST-NAME JOB-TITLE SALARY (1) END-FIND END
572
Programming Guide
There are 7 employees in the Boston offices. 3 (= 42%) are secretaries. ------------------------------------------------------------------------------CURRENT ANNUAL POSITION SALARY -------------------- -------------------- ------------------------- ---------SHAW CREMER COHEN LESLIE WALT JOHN SECRETARY SECRETARY SECRETARY 18000 20000 16000 NAME FIRST-NAME
** Example 'READX04': READ (in combination with FIND and the system ** variables *NUMBER and *COUNTER) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 FIRST-NAME 1 VEHIC-VIEW VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 10 RD. READ EMPLOY-VIEW BY NAME STARTING FROM 'JONES' FD. FIND VEHIC-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (RD.) IF NO RECORDS FOUND ENTER END-NOREC /* DISPLAY NOTITLE *COUNTER (RD.)(NL=8) NAME (AL=15) FIRST-NAME (AL=10) *NUMBER (FD.)(NL=8) *COUNTER (FD.)(NL=8) MAKE END-FIND END-READ END
CNT NAME FIRST-NAME NMBR CNT MAKE --------- --------------- ---------- --------- --------- -------------------1 2 2 3 4 4 5 6 7 8 9 10 JONES JONES JONES JONES JONES JONES JONES JONES JONES JONES JONES JOPER VIRGINIA MARSHA MARSHA ROBERT LILLY LILLY EDWARD MARTHA LAUREL KEVIN GREGORY MANFRED 1 2 2 1 2 2 1 1 1 1 1 0 1 1 2 1 1 2 1 1 1 1 1 0 CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD MG GENERAL MOTORS GENERAL MOTORS GENERAL MOTORS DATSUN FORD
** Example 'LIMITX01': LIMIT (for READ, FIND loop processing) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 1 VEH-VIEW VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 4 * READ EMPLOY-VIEW BY NAME STARTING FROM 'A' FIND VEH-VIEW WITH PERSONNEL-ID = EMPLOY-VIEW.PERSONNEL-ID IF NO RECORDS FOUND MOVE 'NO CAR' TO MAKE END-NOREC DISPLAY PERSONNEL-ID NAME FIRST-NAME MAKE END-FIND END-READ END
574
Programming Guide
Page
04-12-13
14:01:57
PERSONNEL-ID NAME FIRST-NAME MAKE ------------ -------------------- -------------------- -------------------ABELLAN ACHIESON ADAM ADKINSON KEPA ROBERT SIMONE JEFF NO CAR FORD NO CAR GENERAL MOTORS
30000231 20008800
** Example 'ACCEPX04': ACCEPT IF ... LES THAN ... ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 JOB-TITLE 2 SALARY (1) END-DEFINE * LIMIT 20 READ EMPLOY-VIEW BY PERSONNEL-ID = '20017000' ACCEPT IF SALARY (1) LESS THAN 38000 DISPLAY NOTITLE PERSONNEL-ID NAME JOB-TITLE SALARY (1) END-READ END
PERSONNEL NAME CURRENT ANNUAL ID POSITION SALARY --------- -------------------- ------------------------- ---------20017000 20017100 20017400 20017500 20017600 20017700 CREMER MARKUSH NEEDHAM JACKSON PIETSCH PAUL ANALYST TRAINEE PROGRAMMER PROGRAMMER SECRETARY SECRETARY 34000 22000 32500 33000 22000 23000
Programming Guide
575
** Example 'ACCEPX05': ACCEPT IF ... AND ... ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 JOB-TITLE 2 SALARY (1:2) END-DEFINE * LIMIT 6 READ EMPLOY-VIEW PHYSICAL WHERE SALARY(2) > 0 ACCEPT IF SALARY(1) > 10000 AND SALARY(1) < 50000 DISPLAY (AL=15) 'SALARY I' SALARY (1) 'SALARY II' SALARY (2) NAME JOB-TITLE CITY END-READ END
Page SALARY I
1 SALARY II NAME
04-12-13
14:05:28
CURRENT CITY POSITION ---------- ---------- --------------- --------------- --------------48000 45000 48000 36000 46000 40000 46000 32000 SPENGLER SPECK SCHINDLER SCHMIDT SACHBEARBEITER SACHBEARBEITER PROGRAMMIERER SEKRETAERIN DARMSTADT DARMSTADT HEPPENHEIM HEPPENHEIM
576
Programming Guide
** Example 'ACCEPX06': REJECT IF ... OR ... ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 SALARY (1) 2 JOB-TITLE 2 CITY 2 NAME END-DEFINE * LIMIT 20 READ EMPLOY-VIEW LOGICAL BY PERSONNEL-ID = '20017000' REJECT IF SALARY (1) < 20000 OR SALARY (1) > 26000 DISPLAY NOTITLE SALARY (1) NAME JOB-TITLE CITY END-READ END
ANNUAL NAME CURRENT CITY SALARY POSITION ---------- -------------------- ------------------------- -------------------22000 22000 23000 24000 25000 MARKUSH PIETSCH PAUL SMITH LOWRY TRAINEE SECRETARY SECRETARY SECRETARY SECRETARY LOS ANGELES VISTA NORFOLK SILVER SPRING LEXINGTON
Programming Guide
577
** Example 'ATENDX01': AT END OF DATA ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 JOB-TITLE END-DEFINE * READ (6) EMPLOY-VIEW BY PERSONNEL-ID FROM '20017000' DISPLAY NOTITLE NAME JOB-TITLE AT END OF DATA WRITE / 'LAST PERSON SELECTED:' OLD(NAME) END-ENDDATA END-READ END
CURRENT POSITION -------------------- ------------------------CREMER MARKUSH GEE KUNEY NEEDHAM JACKSON ANALYST TRAINEE MANAGER DBA PROGRAMMER PROGRAMMER
NAME
** Example 'ATSTAX02': AT START OF DATA ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 SALARY (1) 2 CURR-CODE (1) 2 BONUS (1,1) END-DEFINE *
578
Programming Guide
ANNUAL BONUS CURRENCY SALARY CODE -------------------- -------------------- ---------- ---------- -------13/12/2004 DE JUAN DE LA MADRID PINERO JAVIER ANSELMO PAULA 1988000 3120000 1756000 0 PTA 0 PTA 0 PTA
NAME
FIRST-NAME
** Example 'WRITEX09': WRITE (in combination with AT END OF DATA ) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 BIRTH 2 JOB-TITLE 2 DEPT END-DEFINE * READ (3) EMPLOY-VIEW BY CITY DISPLAY NOTITLE NAME BIRTH (EM=YYYY-MM-DD) JOB-TITLE WRITE 38T 'DEPT CODE:' DEPT /* AT END OF DATA WRITE / 'LAST PERSON SELECTED:' OLD(NAME) END-ENDDATA SKIP 1 END-READ END
Programming Guide
579
DATE CURRENT OF POSITION BIRTH -------------------- ---------- ------------------------SENKO 1971-09-11 PROGRAMMER DEPT CODE: TECH10 1949-01-09 COMPTABLE DEPT CODE: COMP02 1942-01-01 CONSULTANT DEPT CODE: TECH03
NAME
GODEFROY
CANALE
** Example 'DISPLX13': DISPLAY (compare with WRITEX08 using WRITE) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 SALARY (2) 2 BONUS (1,1) 2 CITY END-DEFINE * LIMIT 2 READ EMPLOY-VIEW WITH CITY = 'CHAPEL HILL' WHERE BONUS(1,1) NE 0 /* DISPLAY 'PERS/ID' PERSONNEL-ID NAME / FIRST-NAME '**' '=' SALARY(1:2) 'BONUS' BONUS(1,1) CITY (AL=15) /* SKIP 1 END-READ END
580
Programming Guide
Page
04-12-13
14:11:28
PERS NAME ANNUAL BONUS CITY ID FIRST-NAME SALARY -------- -------------------- ------------- ---------- --------------20027000 CUMMINGS PUALA 20000200 WOOLSEY LOUISE ** 41000 38900 26000 24700 1500 CHAPEL HILL
**
** Example 'WRITEX08': WRITE (compare with DISPLX13 using DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 SALARY (2) 2 BONUS (1,1) 2 CITY END-DEFINE * LIMIT 2 READ EMPLOY-VIEW WITH CITY = 'CHAPEL HILL' WHERE BONUS(1,1) NE 0 /* WRITE 'PERS/ID' PERSONNEL-ID NAME / FIRST-NAME '**' '=' SALARY(1:2) 'BONUS' BONUS(1,1) CITY (AL=15) /* SKIP 1 END-READ END
Page
04-12-13
14:12:43
PERS/ID 20027000 CUMMINGS PUALA ** ANNUAL SALARY: CHAPEL HILL PERS/ID 20000200 WOOLSEY LOUISE ** ANNUAL SALARY: CHAPEL HILL
41000
38900 BONUS
1500
26000
24700 BONUS
3000
Programming Guide
581
Referenced Example Programs DISPLX14 - DISPLAY statement (with AL, SF and nX)
** Example 'DISPLX14': DISPLAY (with AL, SF and nX) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 FIRST-NAME 2 NAME 2 ADDRESS-LINE (1) 2 TELEPHONE 3 AREA-CODE 3 PHONE 2 CITY END-DEFINE * READ (3) EMPLOY-VIEW BY NAME STARTING FROM 'W' DISPLAY (AL=15 SF=5) NAME CITY / ADDRESS-LINE(1) 2X TELEPHONE SKIP 1 END-READ END
Page NAME
04-12-13
14:14:00
TELEPHONE --------------456452
--------------WABER
WADSWORTH
0332
515365
WAGENBACH
069
983218
582
Programming Guide
Referenced Example Programs WRITEX09 - WRITE statement (in combination with AT END OF DATA)
** Example 'WRITEX09': WRITE (in combination with AT END OF DATA ) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 BIRTH 2 JOB-TITLE 2 DEPT END-DEFINE * READ (3) EMPLOY-VIEW BY CITY DISPLAY NOTITLE NAME BIRTH (EM=YYYY-MM-DD) JOB-TITLE WRITE 38T 'DEPT CODE:' DEPT /* AT END OF DATA WRITE / 'LAST PERSON SELECTED:' OLD(NAME) END-ENDDATA SKIP 1 END-READ END
DATE CURRENT OF POSITION BIRTH -------------------- ---------- ------------------------SENKO 1971-09-11 PROGRAMMER DEPT CODE: TECH10 1949-01-09 COMPTABLE DEPT CODE: COMP02 1942-01-01 CONSULTANT DEPT CODE: TECH03
NAME
GODEFROY
CANALE
Programming Guide
583
DISPLAY Statement
The following example is referenced in the section Page Titles, Page Breaks, Blank Lines. DISPLX21 DISPLAY statement (with slash '/' and compare with WRITE)
** Example 'DISPLX21': DISPLAY (usage of slash '/' in DISPLAY and WRITE) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 NAME 2 FIRST-NAME 2 ADDRESS-LINE (1) END-DEFINE * WRITE TITLE LEFT JUSTIFIED UNDERLINED *TIME 5X 'PEOPLE LIVING IN SALT LAKE CITY' 21X 'PAGE:' *PAGE-NUMBER / 15X 'AS OF' *DAT4E // * WRITE TRAILER UNDERLINED 'REGISTER OF' / 'SALT LAKE CITY' * READ (2) EMPLOY-VIEW WITH CITY = 'SALT LAKE CITY' DISPLAY NAME / FIRST-NAME 'HOME/CITY' CITY 'STREET/OR BOX NO.' ADDRESS-LINE (1) SKIP 1 END-READ END
14:15:50.1
PAGE:
------------------------------------------------------------------------------NAME HOME STREET FIRST-NAME CITY OR BOX NO. -------------------- -------------------- -------------------ANDERSON JENNY SALT LAKE CITY 3701 S. GEORGE MASON
584
Programming Guide
Column Headers
The following example is referenced in the section Column Headers. DISPLX15 - DISPLAY statement (with FC, UC)
** Example 'DISPLX15': DISPLAY (with FC, UC) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 FIRST-NAME 2 NAME 2 ADDRESS-LINE (1) 2 CITY 2 TELEPHONE 3 AREA-CODE 3 PHONE END-DEFINE * FORMAT AL=12 GC== UC=% * READ (3) EMPLOY-VIEW BY NAME STARTING FROM 'R' DISPLAY NOTITLE (FC=*) NAME FIRST-NAME CITY (FC=- UC=-) / ADDRESS-LINE(1) TELEPHONE SKIP 1 END-READ END
****NAME**** *FIRST-NAME* ----CITY---- ========TELEPHONE======== **ADDRESS*** ****AREA**** *TELEPHONE** ****CODE**** %%%%%%%%%%%% %%%%%%%%%%%% ------------ %%%%%%%%%%%% %%%%%%%%%%%% RACKMANN MARIAN FRANKFURT 069 FINKENSTR. 1 375849
Programming Guide
585
RAMAMOORTHY
TY
175-1885
RAMAMOORTHY
TIMMIE
151-4673
** Example 'DISPLX16': DISPLAY (with '/', 'text', 'text/text') ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 FIRST-NAME 2 NAME 2 ADDRESS-LINE (1) 2 CITY 2 TELEPHONE 3 AREA-CODE 3 PHONE END-DEFINE * READ (5) EMPLOY-VIEW BY NAME STARTING FROM 'E' DISPLAY NOTITLE '/' NAME (AL=12) /* suppressed header 'FIRST/NAME' FIRST-NAME (AL=10) /* two-line user-defined header 'ADDRESS' CITY / /* user-defined header ' ' ADDRESS-LINE(1) /* 'blank' header TELEPHONE (HC=L) /* default header SKIP 1 END-READ END
FIRST NAME
ADDRESS
TELEPHONE
AREA TELEPHONE CODE ---------- -------------------- ------ --------------EAVES TREVOR DERBY 17 HARTON ROAD OBERRAMSTADT FORSTWEG 22 DARMSTADT BRESLAUERPL. 4 0332 657623
ECKERT
KARL
06154
99722
ECKHARDT
RICHARD
586
Programming Guide
EDMUNDSON
LES
918
945-4916
EGGERT
HERMANN
0711
981237
Field-Output-Relevant Parameters
The following examples are referenced in the section Parameters to Influence the Output of Fields. They are provided to demonstrate the use of the parameters LC, IC, TC, AL, NL, IS, ZP and ES, and the SUSPEND IDENTICAL SUPPRESS statement: DISPLX17 - DISPLAY statement (with NL, AL, IC, LC, TC)
** Example 'DISPLX17': DISPLAY (with NL, AL, IC, LC, TC) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 FIRST-NAME 2 NAME 2 SALARY (1) 2 BONUS (1,1) END-DEFINE * READ (3) EMPLOY-VIEW BY NAME STARTING FROM 'JONES' DISPLAY NOTITLE (IS=ON NL=15) NAME '-' '=' FIRST-NAME (AL=12) 'ANNUAL SALARY' SALARY(1) (LC=USD TC=.00) / '+ BONUSES' BONUS(1,1) (IC='+ ' TC=.00) SKIP 1 END-READ END
ANNUAL SALARY + BONUSES -------------------- -------------- ---------------------JONES - VIRGINIA USD + - MARSHA USD 46000.00 9000.00 50000.00
NAME
FIRST-NAME
Programming Guide
587
31000.00 + 0.00
DISPLX18 - DISPLAY statement (using default settings for SF, AL, UC, LC, IC, TC and compare with DISPLX19)
** Example 'DISPLX18': DISPLAY (using default settings for SF, AL, UC, ** LC, IC, TC and compare with DISPLX19) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 SALARY (1) 2 BONUS (1,1) END-DEFINE * FIND (6) EMPLOY-VIEW WITH CITY = 'CHAPEL HILL' DISPLAY NAME FIRST-NAME SALARY(1) BONUS(1,1) END-FIND END
Page
1 NAME FIRST-NAME
04-12-13
14:20:48
ANNUAL BONUS SALARY -------------------- -------------------- ---------- ---------KESSLER ADKINSON GEE HERZOG QUILLION CUMMINGS CLARE DAVID TOMMIE JOHN TIMOTHY PUALA 41000 24000 39500 31500 30500 41000 0 0 0 0 0 1500
588
Programming Guide
Referenced Example Programs DISPLX19 - DISPLAY statement (with SF, AL, LC, IC, TC and compare with DISPLX18)
** Example 'DISPLX19': DISPLAY (with SF, AL, LC, IC, TC and compare ** with DISPLX19) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 FIRST-NAME 2 CITY 2 SALARY (1) 2 BONUS (1,1) END-DEFINE * FORMAT SF=3 AL=15 UC== * FIND (6) EMPLOY-VIEW WITH CITY = 'CHAPEL HILL' DISPLAY (NL=10) NAME FIRST-NAME (LC='- ' UC=-) SALARY (1) (LC=USD) BONUS (1,1) (IC='*** ' TC=' ***') END-FIND END
Page NAME
1 FIRST-NAME ----------------CLARE DAVID TOMMIE JOHN TIMOTHY PUALA ANNUAL SALARY ============== USD USD USD USD USD USD 41000 24000 39500 31500 30500 41000
04-12-13 BONUS
14:21:57
=================== *** 0 *** 0 *** 0 *** 0 *** 0 *** 1500 *** *** *** *** *** ***
Programming Guide
589
Referenced Example Programs SUSPEX01 - SUSPEND IDENTICAL SUPPRESS statement (in conjunction with parameters IS, ES, ZP in DISPLAY)
** Example 'SUSPEX01': SUSPEND IDENTICAL SUPPRESS (in conjunction with ** parameters IS, ES, ZP in DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 CITY 1 VEH-VIEW VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 15 RD. READ EMPLOY-VIEW BY NAME STARTING FROM 'JONES' SUSPEND IDENTICAL SUPPRESS FD. FIND VEH-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (RD.) IF NO RECORDS FOUND MOVE '******' TO MAKE END-NOREC DISPLAY NOTITLE (ES=OFF IS=ON ZP=ON AL=15) NAME (RD.) FIRST-NAME (RD.) MAKE (FD.) (IS=OFF) END-FIND END-READ END
NAME FIRST-NAME MAKE --------------- --------------- --------------JONES JONES JONES JONES JONES JONES JONES JONES JONES JOPER VIRGINIA MARSHA ROBERT LILLY EDWARD MARTHA LAUREL KEVIN GREGORY MANFRED CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD MG GENERAL MOTORS GENERAL MOTORS GENERAL MOTORS DATSUN FORD ******
590
Programming Guide
SUSPEX02 - SUSPEND IDENTICAL SUPPRESS statement (in conjunction with parameters IS, ES, ZP in DISPLAY) Identical to SUSPEX01, but with IS=OFF.
** Example 'SUSPEX02': SUSPEND IDENTICAL SUPPRESS (in conjunction with ** parameters IS, ES, ZP in DISPLAY) ** Identical to SUSPEX01, but with IS=OFF. ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 CITY 1 VEH-VIEW VIEW OF VEHICLES 2 PERSONNEL-ID 2 MAKE END-DEFINE * LIMIT 15 RD. READ EMPLOY-VIEW BY NAME STARTING FROM 'JONES' SUSPEND IDENTICAL SUPPRESS FD. FIND VEH-VIEW WITH PERSONNEL-ID = PERSONNEL-ID (RD.) IF NO RECORDS FOUND MOVE '******' TO MAKE END-NOREC DISPLAY NOTITLE (ES=OFF IS=OFF ZP=ON AL=15) NAME (RD.) FIRST-NAME (RD.) MAKE (FD.) (IS=OFF) END-FIND END-READ END
NAME FIRST-NAME MAKE --------------- --------------- --------------JONES JONES JONES JONES JONES VIRGINIA MARSHA MARSHA ROBERT LILLY CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD
Programming Guide
591
** Example 'COMPRX03': COMPRESS (using parameters LC and TC) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 SALARY (1) 2 CURR-CODE (1) 2 LEAVE-DUE 2 NAME 2 FIRST-NAME 2 JOB-TITLE * 1 #SALARY (N9) 1 #FULL-SALARY (A25) 1 #VACATION (A11) END-DEFINE * READ (3) EMPLOY-VIEW WITH CITY = 'BOSTON' MOVE SALARY(1) TO #SALARY COMPRESS 'SALARY :' CURR-CODE(1) #SALARY INTO #FULL-SALARY COMPRESS 'VACATION:' LEAVE-DUE INTO #VACATION /* DISPLAY NOTITLE NAME FIRST-NAME 'JOB DESCRIPTION' JOB-TITLE (LC='JOB : ') / '/' #FULL-SALARY / '/' #VACATION (TC='DAYS') SKIP 1 END-READ END
592
Programming Guide
NAME FIRST-NAME JOB DESCRIPTION -------------------- -------------------- ----------------------------------SHAW LESLIE JOB : SECRETARY SALARY : USD 18000 VACATION: 2DAYS JOB : PROGRAMMER SALARY : USD 31000 VACATION: 1DAYS JOB : SECRETARY SALARY : USD 20000 VACATION: 3DAYS
STANWOOD
VERNON
CREMER
WALT
Edit Masks
The following examples are referenced in the section Edit Masks - EM Parameter. EDITMX03 - Edit mask (different EM for alpha-numeric fields)
** Example 'EDITMX03': Edit mask (different EM for alpha-numeric fields) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 CITY 2 SALARY(1) END-DEFINE * LIMIT 3 READ EMPLOY-VIEW BY PERSONNEL-ID FROM '20018000' WHERE SALARY(1) = 28000 THRU 30000 DISPLAY 'N A M E' NAME (EM=X^^X^^X^^X^^X^^X^^X^^X^^X^^X^^X) / 'NAME HEX' NAME (EM=H^H^H^H^H^H^H^H^H^H^H) FIRST-NAME (EM=' - 'X(15)*) CITY (EM=X..X(10)) SKIP 1 END-READ END
Programming Guide
593
Page
04-12-13
14:26:57
N A M E FIRST-NAME CITY NAME HEX -------------------------------- ------------------ ------------L O R I E - JEAN-PAUL D3 D6 D9 C9 C5 40 40 40 40 40 40 H A L L - ARTHUR C8 C1 D3 D3 40 40 40 40 40 40 40 V A S W A N I - TOMMIE E5 C1 E2 E6 C1 D5 C9 40 40 40 40 * C..LEVELAND
* A..NN ARBER
* M..ONTERREY
** Example 'EDITMX04': Edit mask (different EM for numeric fields) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 FIRST-NAME 2 NAME 2 SALARY (1) 2 BONUS (1,1) 2 LEAVE-DUE END-DEFINE * LIMIT 2 READ EMPLOY-VIEW BY PERSONNEL-ID = '20018000' WHERE SALARY(1) = 28000 THRU 30000 DISPLAY (SF=4) 'N A M E' NAME 'SALARY' SALARY(1) (EM=*USD^ZZZ,999) 'BONUS (ZZ)' BONUS(1,1) (EM=S*ZZZ,999) / 'BONUS (Z9)' BONUS(1,1) (EM=SZ99,999+) / '->' '=' BONUS(1,1) (EM=-999,999) 'VAC/DUE' LEAVE-DUE (EM=+999) SKIP 1 END-READ END
594
Programming Guide
Page
1 N A M E SALARY BONUS (ZZ) BONUS (Z9) BONUS ----------+**4,000 + 04,000+ -> 004,000 +**5,000 + 05,000+ -> 005,000 VAC DUE --+13
04-12-13
14:27:43
-------------------LORIE
----------USD *28,000
HALL
USD *30,000
+14
EDITMX05 - Edit mask (EM for date and time system variables)
** Example 'EDITMX05': Edit mask (EM for date and time system variables) ************************************************************************ WRITE NOTITLE // 'DATE INTERNAL :' *DATX (DF=L) / ' :' *DATX (EM=N(9)' 'ZW.'WEEK 'YYYY) / ' :' *DATX (EM=ZZJ'.DAY 'YYYY) / ' ROMAN :' *DATX (EM=R) / ' AMERICAN :' *DATX (EM=MM/DD/YYYY) 12X 'OR ' *DAT4U / ' JULIAN :' *DATX (EM=YYYYJJJ) 15X 'OR ' *DAT4J / ' GREGORIAN:' *DATX (EM=ZD.''L(10)''YYYY) 5X 'OR ' *DATG /// 'TIME INTERNAL :' *TIMX 14X 'OR ' *TIME / ' :' *TIMX (EM=HH.II.SS.T) / ' :' *TIMX (EM=HH.II.SS' 'AP) / ' :' *TIMX (EM=HH) END
2004-12-13 Monday 51.WEEK 2004 348.DAY 2004 MMIV 12/13/2004 2004348 13.December2004
OR OR OR
OR
14:28:49.1
Programming Guide
595
** Example 'WRITEX10': WRITE (with nT, T*field and P*field) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 JOB-TITLE 2 NAME 2 SALARY (1) 2 BONUS (1,1) END-DEFINE * READ (3) EMPLOY-VIEW WITH JOB-TITLE FROM 'SALES PERSON' DISPLAY NOTITLE NAME 30T JOB-TITLE VERT AS 'SALARY/BONUS' SALARY(1) BONUS(1,1) AT BREAK OF JOB-TITLE WRITE 20T 'AVERAGE' T*JOB-TITLE OLD(JOB-TITLE) (AL=15) '(SAL)' P*SALARY AVER(SALARY(1)) / 46T '(BON)' P*BONUS AVER(BONUS(1,1)) / END-BREAK SKIP 1 END-READ END
NAME -------------------SAMUELSON
CURRENT SALARY POSITION BONUS ------------------------- ---------SALES PERSON 32000 6000 34000 7000 38000 9000 (SAL) (BON) 34666 7333
PAPAYANOPOULOS
SALES PERSON
HELL
SALES PERSON
AVERAGE
SALES PERSON
596
Programming Guide
AT BREAK Statement
The following example is referenced in the section Control Breaks. ATBREX06 - AT BREAK OF statement (comparing NMIN, NAVER, NCOUNT with MIN, AVER, COUNT)
** Example 'ATBREX06': AT BREAK OF (comparing NMIN, NAVER, NCOUNT with ** MIN, AVER, COUNT) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 SALARY (1:2) END-DEFINE * WRITE TITLE '-- SALARY STATISTICS BY CITY --' / * READ (2) EMPLOY-VIEW WITH CITY = 'NEW YORK' DISPLAY CITY 'SALARY (1)' SALARY(1) 15X 'SALARY (2)' SALARY(2) AT BREAK OF CITY WRITE / 14T 'S A L A R Y (1)' 39T 'S A L A R Y (2)' / 13T 'MIN:' MIN(SALARY(1)) 38T 'MIN:' MIN(SALARY(2)) / 13T '- AVER:' AVER(SALARY(1)) 38T '- AVER:' AVER(SALARY(2)) / 16T COUNT(SALARY(1)) 'RECORDS' 41T COUNT(SALARY(2)) 'RECORDS' // 13T '- NMIN:' NMIN(SALARY(1)) 38T '- NMIN:' NMIN(SALARY(2)) / 13T '- NAVER:' NAVER(SALARY(1)) 38T '- NAVER:' NAVER(SALARY(2)) / 16T NCOUNT(SALARY(1)) 'RECORDS' 41T NCOUNT(SALARY(2)) 'RECORDS' END-BREAK END-READ END
-- SALARY STATISTICS BY CITY -CITY SALARY (1) -------------------- ---------NEW YORK NEW YORK 17000 38000 S A L A R Y (1) MIN: 17000 AVER: 27500 2 RECORDS SALARY (2) ---------16100 34900 S A L A R Y (2) MIN: 16100 AVER: 25500 2 RECORDS
Programming Guide
597
- NMIN: - NAVER:
- NMIN: - NAVER:
** Example 'WRITEX11': WRITE (with nX, n/n and COMPRESS) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 SALARY (1) 2 FIRST-NAME 2 NAME 2 CITY 2 ZIP 2 CURR-CODE (1) 2 JOB-TITLE 2 LEAVE-DUE 2 ADDRESS-LINE (1) * 1 #SALARY (A8) 1 #FULL-NAME (A25) 1 #FULL-CITY (A25) 1 #FULL-SALARY (A25) 1 #VACATION (A16) END-DEFINE * READ (3) EMPLOY-VIEW LOGICAL BY PERSONNEL-ID = '2001800' MOVE SALARY(1) TO #SALARY COMPRESS FIRST-NAME NAME INTO #FULL-NAME COMPRESS ZIP CITY INTO #FULL-CITY COMPRESS 'SALARY :' CURR-CODE(1) #SALARY INTO #FULL-SALARY COMPRESS 'VACATION:' LEAVE-DUE 'DAYS' INTO #VACATION /* DISPLAY NOTITLE 'NAME AND ADDRESS' NAME 5X 'PERS-NO.' PERSONNEL-ID 3X 'JOB TITLE' JOB-TITLE (LC='JOB : ') WRITE 1/5 #FULL-NAME 1/37 #FULL-SALARY 2/5 ADDRESS-LINE(1) 2/37 #VACATION 3/5 #FULL-CITY SKIP 1
598
Programming Guide
NAME AND ADDRESS -------------------FARRIS JACKIE FARRIS 918 ELM STREET 32306 TALLAHASSEE EVANS JO EVANS 1058 REDSTONE LANE 68508 LINCOLN
PERS-NO. -------20018000
20018100
HERZOG 20018200 JOHN HERZOG 255 ZANG STREET #253 27514 CHAPEL HILL
IFX03 - IF statement
** Example 'IFX03': IF ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 NAME 2 CITY 2 BONUS (1,1) 2 SALARY (1) * 1 #INCOME (N9) 1 #TEXT (A26) END-DEFINE * WRITE TITLE '-- DISTRIBUTION OF CATALOGS I AND II --' / * READ (3) EMPLOY-VIEW BY CITY = 'SAN FRANSISCO' COMPUTE #INCOME = BONUS(1,1) + SALARY(1) /* IF #INCOME > 40000 MOVE 'CATALOGS I AND II' TO #TEXT ELSE MOVE 'CATALOG I' TO #TEXT END-IF /*
Programming Guide
599
56000 0 ---------INCOME: 56000 =================== 9150 0 ---------INCOME: 9150 =================== 13500 600 ---------INCOME: 14100 ===================
CATALOGS I AND II
RICHMOND
CATALOG I
MONKTON
CATALOG I
** Example 'COMPRX03': COMPRESS (using parameters LC and TC) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 SALARY (1) 2 CURR-CODE (1) 2 LEAVE-DUE 2 NAME 2 FIRST-NAME 2 JOB-TITLE * 1 #SALARY (N9)
600
Programming Guide
NAME FIRST-NAME JOB DESCRIPTION -------------------- -------------------- ----------------------------------SHAW LESLIE JOB : SECRETARY SALARY : USD 18000 VACATION: 2DAYS JOB : PROGRAMMER SALARY : USD 31000 VACATION: 1DAYS JOB : SECRETARY SALARY : USD 20000 VACATION: 3DAYS
STANWOOD
VERNON
CREMER
WALT
System Variables
The following examples are referenced in the section System Variables and System Functions.
Programming Guide
601
Referenced Example Programs EDITMX05 - Edit mask (EM for date and time system variables)
** Example 'EDITMX05': Edit mask (EM for date and time system variables) ************************************************************************ WRITE NOTITLE // 'DATE INTERNAL :' *DATX (DF=L) / ' :' *DATX (EM=N(9)' 'ZW.'WEEK 'YYYY) / ' :' *DATX (EM=ZZJ'.DAY 'YYYY) / ' ROMAN :' *DATX (EM=R) / ' AMERICAN :' *DATX (EM=MM/DD/YYYY) 12X 'OR ' *DAT4U / ' JULIAN :' *DATX (EM=YYYYJJJ) 15X 'OR ' *DAT4J / ' GREGORIAN:' *DATX (EM=ZD.''L(10)''YYYY) 5X 'OR ' *DATG /// 'TIME INTERNAL :' *TIMX 14X 'OR ' *TIME / ' :' *TIMX (EM=HH.II.SS.T) / ' :' *TIMX (EM=HH.II.SS' 'AP) / ' :' *TIMX (EM=HH) END
2004-12-13 Monday 51.WEEK 2004 348.DAY 2004 MMIV 12/13/2004 2004348 13.December2004
OR OR OR
TIME INTERNAL : : : :
OR
14:36:58.8
READX04 - READ statement (in combination with FIND and the system variables *NUMBER and *COUNTER)
** Example 'READX04': READ (in combination with FIND and the system ** variables *NUMBER and *COUNTER) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 FIRST-NAME 1 VEHIC-VIEW VIEW OF VEHICLES
602
Programming Guide
CNT NAME FIRST-NAME NMBR CNT MAKE --------- --------------- ---------- --------- --------- -------------------1 2 2 3 4 4 5 6 7 8 9 10 JONES JONES JONES JONES JONES JONES JONES JONES JONES JONES JONES JOPER VIRGINIA MARSHA MARSHA ROBERT LILLY LILLY EDWARD MARTHA LAUREL KEVIN GREGORY MANFRED 1 2 2 1 2 2 1 1 1 1 1 0 1 1 2 1 1 2 1 1 1 1 1 0 CHRYSLER CHRYSLER CHRYSLER GENERAL MOTORS FORD MG GENERAL MOTORS GENERAL MOTORS GENERAL MOTORS DATSUN FORD
** Example 'WTITLX01': WRITE TITLE (with *PAGE-NUMBER) ************************************************************************ DEFINE DATA LOCAL 1 VEHIC-VIEW VIEW OF VEHICLES 2 MAKE 2 YEAR 2 MAINT-COST (1) END-DEFINE * LIMIT 5 *
Programming Guide
603
YEAR: 1980 PAGE 1 YEAR MAKE MAINT-COST ----- -------------------- ---------1980 RENAULT 1980 RENAULT 1980 PEUGEOT 20000 20000 20000
System Functions
The following examples are referenced in the section System Variables and System Functions. ATBREX06 - AT BREAK OF statement (comparing NMIN, NAVER, NCOUNT with MIN, AVER, COUNT)
** Example 'ATBREX06': AT BREAK OF (comparing NMIN, NAVER, NCOUNT with ** MIN, AVER, COUNT) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 CITY 2 SALARY (1:2) END-DEFINE * WRITE TITLE '-- SALARY STATISTICS BY CITY --' / * READ (2) EMPLOY-VIEW WITH CITY = 'NEW YORK' DISPLAY CITY 'SALARY (1)' SALARY(1) 15X 'SALARY (2)' SALARY(2) AT BREAK OF CITY WRITE /
604
Programming Guide
-- SALARY STATISTICS BY CITY -CITY SALARY (1) -------------------- ---------NEW YORK NEW YORK 17000 38000 S A L A R Y (1) MIN: 17000 AVER: 27500 2 RECORDS 17000 27500 2 RECORDS SALARY (2) ---------16100 34900 S A L A R Y (2) MIN: 16100 AVER: 25500 2 RECORDS 16100 25500 2 RECORDS
- NMIN: - NAVER:
- NMIN: - NAVER:
ATENPX01 - AT END OF PAGE statement (with system function available via GIVE SYSTEM FUNCTIONS in DISPLAY)
** Example 'ATENPX01': AT END OF PAGE (with system function available ** via GIVE SYSTEM FUNCTIONS in DISPLAY) ************************************************************************ DEFINE DATA LOCAL 1 EMPLOY-VIEW VIEW OF EMPLOYEES 2 PERSONNEL-ID 2 NAME 2 JOB-TITLE 2 SALARY (1) END-DEFINE * READ (10) EMPLOY-VIEW BY PERSONNEL-ID = '20017000' DISPLAY NOTITLE GIVE SYSTEM FUNCTIONS NAME JOB-TITLE 'SALARY' SALARY(1) /* AT END OF PAGE
Programming Guide
605
CURRENT SALARY POSITION -------------------- ------------------------- ---------CREMER MARKUSH GEE KUNEY NEEDHAM JACKSON PIETSCH PAUL HERZOG DEKKER ANALYST TRAINEE MANAGER DBA PROGRAMMER PROGRAMMER SECRETARY SECRETARY MANAGER DBA AVERAGE SALARY: ... 34000 22000 39500 40200 32500 33000 22000 23000 48500 48000 34270
NAME
606
Programming Guide
Index
L
label, 343
P
Programming Guide, 1
607
608