04
Mon, Nov
1 New Articles

How to Use Variable-Length Fields

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Variable-length fields are used to reduce storage utilization for fields that may not always be filled with data. Good candidates for a variable-length field include a text description or a note field in an item master file. The maximum length of a variable-length field is 32,740 characters.

Declaring Variable-Length Fields in DDS

To declare a variable-length field in a database file, use the VARLEN keyword. For example:


     A          ITEMREC
     A            ITEMNO         7P 0                     
     A            DESC          30A
     A            NOTES        250A          VARLEN(20)


The VARLEN keyword is used with standard character fields. When VARLEN is specified, the character field becomes a variable-length field with the capability to store up to its length in data. But rather than allocate storage in each database record for the variable-length field's data (250 bytes of data in my example), storage for these fields is not allocated. Instead, a variable-length storage area is created in the file. This area contains only enough space to store the data contained in the variable-length fields. This provides more-efficient storage for the database file.

The VARLEN keyword accepts one optional parameter that indicates the number of bytes for the initial allocation of the field. This initial allocation is actually stored in the regular area of the database file with the other fields. It provides more-efficient access to the data in the field that is not longer than this initial length. If a field is normally empty (unspecified), there is no need to specify an initial length. If a field is generally going to contain 1 to 20 characters on average, then specify an initial length of 20.

In my 250-byte variable-length field, an initial allocation of 10 bytes is specified. This initial allocation is the portion of the field that is stored in the so-called fixed portion of the file, whereas the rest of the variable-length field is stored in the variable portion of the file. If a field normally contains X bytes or less, but occasionally exceeds X bytes, declare a variable-length field with the maximum length you may need and specify an initial allocation size of X.

Using Variable-Length Fields in RPG

RPG IV has integrated support for variable-length fields, whereas RPG III support is simulated.

In RPG III, variable-length fields are not directly supported. To use them, the OPTION(*VARCHAR) keyword must be specified on the CRTRPGPGM command. This keyword option, however, only causes the compiler to translate a variable-length field from a database file to an RPG III character field. To access the field correctly, you need to create an Input specification with two subfields.


0001 INOTES       DS
0002 I                                    B   1   20NTLEN
0003 I                                    A   3 252 NTDATA

The first field, NTLEN, is the field's current length. The second field, NTDATA, is the data itself. In RPG III, it is up to the programmer to manage the current length of a variable-length field. Perhaps this is why so many RPG programmers have been put off and do not use variable-length fields.

The name of the data structure (line 1) is NOTES and must be the name of a field in a database file used in this program. That field must be declared in its DDS with the VARLEN keyword. The DDS definition would look something like this:

     A            NOTES        250A          VARLEN


In RPG IV, variable-length field support is integrated, so no special data structure or manipulation is needed. To declare a variable-length field in RPG IV, use a Definition specification and add the VARYING keyword to the field definition, as follows:

     D Notes           S          10000A   Inz('Bob') VARYING


This declares a variable-length field named NOTES with up to 10,000 characters.

Variable-length fields in RPG IV have data, a declared length, and a current length. The declared length is just what you might think: the length of the field as declared on the Definition specification. In my NOTES field, the declared length is 10,000 characters. The current length of the field is the length assigned to the field at any given point. If the INZ keyword is used, the data in the INZ keyword is the initial value and is used to set the current length when the program is started. In my example, the current length of NOTES is 3 when the program is started. Unlike DDS's VARLEN keyword, the RPG IV VARYING keyword does not support an initial allocation length parameter.

Variable-Length Fields and Opcodes

To assign data to a variable-length field, use the EVAL, EVALR, MOVE, or MOVEL operation codes. When you use the EVAL or EVALR operation code to move data into a variable-length field, the current length of the field adjusts to the length of the data being moved. However, the MOVE or MOVEL operation codes treat variable-length fields like fixed-length fields. That is, they do not adjust the current length of the variable-length fields.

The EVAL operation code changes the length of a variable-length field. When data is copied to the variable-length field or when a numeric value is assigned to the %LEN for the variable-length field, the EVAL operation code adjusts the current length of the variable-length field.

0001 C                   Eval      Notes = 'Clearance sale!' 
0002 C                   Eval      %Len(Notes) = 10 

Line 1 copies a text string to the NOTES field. The EVAL opcode copies the data to the field and sets the variable-length field's length to 15--the string it copied. After line 1 is run, the NOTES field's length is 15.

Line 2 uses the %LEN built-in function to set the length of the field to 10. Therefore the data in the field after line 2 is performed is 'Clearance '.

Why change the current length of a variable-length field? To allow the MOVE and MOVEL operation codes to operate with these types of fields with a known length.

Variable-length fields can be used not only to save space but also to simplify passing parameters to procedures. By specifying VARYING for a character parameter of a procedure along with either CONST or VALUE, you can specify a fixed- or variable-length field for that parameter. The lengths of the values passed to the procedure may be as short as 1 position or as long as the declared parameter length. The compiler converts the data into the procedure's internally required form.

Consider the prototype for the TOUPPER procedure, as follows:

0001 D ToUpper         PR          2048A   VARYING
0002 D  InputStg                   2048A   VARYING VALUE 


The INPUTSTG parameter is declared as 2048-byte variable-length field that is passed by value. A fixed-length value (including a field or data structure), a constant or literal, or a variable-length field may be passed on this parameter. The procedure itself receives the data as a variable-length field and can process it accordingly.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: