29
Fri, Nov
0 New Articles

Flexible Character String Search with OPNQRYF

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

Putting OPNQRYF's wild card function to work.

Brief: There are numerous ways you can scan character fields in an AS/400 database to find a pattern. The method presented here, although not the most conventional, may be one you should consider.

When you need to select records from a database file based on character string pattern matching, you basically have five choices (unless you purchase add-on products like SQL or Query/400). You can use the Copy File (CPYF) command with the ConTains (*CT) operator, use the QCLSCAN API, use Query Management, write your own HLL program or use the Open Query File (OPNQRYF) command. OPNQRYF may not be the first method that comes to mind, but it very well might be the best choice.

Consider the disadvantages of some of the options. The CPYF command doesn't provide wild card characters. The QCLSCAN API, while powerful, requires several parameters. Most programmers don't know the complexities of Query Management. Finally, writing a HLL program creates a somewhat static solution (e.g., file formats must be established at compile time).

On the other hand, record selection with OPNQRYF is easy to code, allows you to create flexible search criteria and can provide dynamic selection criteria by using variables to build the selection expressions, file names and field names.

Actually, OPNQRYF can employ two methods to perform character string pattern matching: the *CT operation method or the wild card (%WLDCRD) function method. I will use the %WLDCRD method since it offers more powerful pattern-matching capabilities.

To illustrate how to use OPNQRYF's %WLDCRD function, I have developed the Create Subset of File (CRTSSETF) command. It allows you to create a subset of any physical file based on a character string match against any character field of a file. Before I describe the command in detail, let's take a look at the %WLDCRD function.

The Wild Card Function

Selection of records via OPNQRYF is accomplished by submitting selection expressions through the QRYSLT parameter. Flexibility and power is added to the expression by incorporating the %WLDCRD function.

Like the %RANGE and %VALUES functions, %WLDCRD can be used only on the right side of a QRYSLT or GRPSLT expression. The left-hand side of the expression must contain a character field and the logical operator can only be EQual (*EQ or =).

For example, let's say you want to select all records from the CUSTMAST file where the company name field (CMNAME) contains "COMPUTER" anywhere within the field. The OPNQRYF command would look like this:

 OPNQRYF FILE((CUSTMAST)) + QRYSLT('CMNAME *EQ + %WLDCRD("*COMPUTER*")') 

The asterisks on each side of COMPUTER are the wild cards which cause the occurrence of the word (COMPUTER) anywhere within the field to be considered a match. Not only is this simple to code, but the selection processing time is very good. As an example, I ran a test on a dedicated D20 where I compared the OPNQRYF command using the %WLDCRD function with an RPG program that used the SCAN operation. I searched a 185,000-record file for a character string. When the number of records matching the selection criteria was small, OPNQRYF was slightly faster than the RPG program.

When the number of matched records was large (over 50,000), the RPG program was faster. 113,644 records were selected in two minutes by the RPG program versus three minutes by OPNQRYF. The performance of OPNQRYF was very acceptable, especially considering that the RPG program method doesn't allow wild cards, doesn't provide for dynamic file opens, and therefore must be hard-coded for a particular file.

%WLDCRD can use two separate wild card characters. By default, the pattern string you look for contains an underscore character (' _ ') and an asterisk ('*') as wild card characters. The underscore is interpreted as a fixed, one- character wild card-meaning that any single character is considered to match the underscore. The asterisk, on the other hand, is a flexible wild card, which can match any number of characters (even zero characters).

To illustrate, '_AT' (using the single-character, fixed wild card), matches BAT, CAT, EAT, FAT, and so on, but not SEAT, since 'SE' is two characters and ' _ ', the fixed wild card, represents only one character. However, '*AT' matches everything '_AT' would match, plus other words like SEAT, CHEAT or even AT and MONTSERRAT, since '*' can be replaced by any number of characters-even no characters. Now let's take a look at the format of the %WLDCRD function in 1.

To illustrate, '_AT' (using the single-character, fixed wild card), matches BAT, CAT, EAT, FAT, and so on, but not SEAT, since 'SE' is two characters and ' _ ', the fixed wild card, represents only one character. However, '*AT' matches everything '_AT' would match, plus other words like SEAT, CHEAT or even AT and MONTSERRAT, since '*' can be replaced by any number of characters-even no characters. Now let's take a look at the format of the %WLDCRD function in Figure 1.

The optional wild card characters parameter increases the flexibility of the %WLDCRD function by letting you select which characters to use for wild cards. The default characters are '_' for the single-character wild card and '*' for the flexible wild card character, as explained above. Most of the time, you can use the default values, but suppose you need to look for a character string that actually contains an embedded asterisk? Since the asterisk is a wild card character by default, it would seem that you have a problem.

%WLDCRD, however, lets you avoid the conflict by selecting another character as the wild card. Therefore, when you need to scan for an underscore character or an asterisk, you may substitute any character you like. The %WLDCRD function then uses your character(s) as the wild card characters.

If you specify a replacement character for one of the default wild card characters, you must specify both wild cards. This means that the second parameter of the %WLDCRD function must have two characters or none at all.

To illustrate, let's say you want to scan for the occurrence of an asterisk ('*') in any customer name in the CUSTMAST file. Since the character string contains an asterisk, we'll use an ampersand ('&') character for the substring wild card character. The OPNQRYF command would look like this:

 OPNQRYF FILE((CUSTMAST)) + QRYSLT('CMNAME *EQ + %WLDCRD("&*&" "_&")') 

Even though I didn't replace the default single-character wild card (' _ ') with a different character, I still had to include it.

The CRTSSETF Command

Rather than creating a new OPNQRYF command each time you want to subset a file, you can use the command I've created. With CRTSSETF, you can quickly and easily create a subset of any file by scanning for a character string up to 25 characters in length. 2 shows the prompting for the command. You must submit a qualified file name to be used as input, followed by the name of a character field that is to be scanned. By default, the target field will be translated to uppercase before the search string is compared to it. For a case- sensitive search, simply change the translate parameter value to *NO. You specify the source string for the search and replace the default wild cards, if necessary.

Rather than creating a new OPNQRYF command each time you want to subset a file, you can use the command I've created. With CRTSSETF, you can quickly and easily create a subset of any file by scanning for a character string up to 25 characters in length. Figure 2 shows the prompting for the command. You must submit a qualified file name to be used as input, followed by the name of a character field that is to be scanned. By default, the target field will be translated to uppercase before the search string is compared to it. For a case- sensitive search, simply change the translate parameter value to *NO. You specify the source string for the search and replace the default wild cards, if necessary.

The remaining parameters relate to the outfile. You can create a subset of the file, or you can add to or replace the records of an existing member. 3 contains the command source member.

The remaining parameters relate to the outfile. You can create a subset of the file, or you can add to or replace the records of an existing member. Figure 3 contains the command source member.

4 contains the source member for the command processing program. The OPNQRYF command carries out the selection of records, and the Copy from Query File (CPYFRMQRYF) command performs the actual creation of the file.

Figure 4 contains the source member for the command processing program. The OPNQRYF command carries out the selection of records, and the Copy from Query File (CPYFRMQRYF) command performs the actual creation of the file.

You might consider making modifications to the command to make it even more powerful. For example, you could allow a list of fields to be submitted for the scan instead of just one.

OPNQRYF is Powerful

As you can see, it is very easy to create global scanning programs using the OPNQRYF command. The real work in the CRTSSETF command is done by one statement-the OPNQRYF command incorporating the %WLDCRD function. The bottom line...if you aren't already using OPNQRYF for your scan selections, you should consider it.

Richard Shaler is a senior technical editor at Midrange Computing.


Flexible Character String Search with OPNQRYF

Figure 1 Format for Wild Card Function of OPNQRYF

 %WLDCRD(''pattern_string'' [''wild_card_characters'']) 
Flexible Character String Search with OPNQRYF

Figure 2 The CRTSSETF Prompt

 Create Subset of File (CRTSSETF) Type choices, press Enter. File . . . . . . . . . . . . . . __________ Name Library . . . . . . . . . . . *LIBL_____ Name, *LIBL Character field to search . . . __________ Character value Translate field to uppercase . . *YES *YES, *NO Search string . . . . . . . . . _________________________ Single character wild card . . . '_' Character value Substring wild card . . . . . . '*' Character value Outfile . . . . . . . . . . . . __________ Name Library . . . . . . . . . . . QTEMP_____ Name Create file . . . . . . . . . . *NO *YES, *NO Member . . . . . . . . . . . . . *FIRST____ Name, *FIRST Member option . . . . . . . . . *REPLACE *ADD, *REPLACE Bottom F3=Exit F4=Prompt F5=Refresh F12=Cancel F13=How to use this display F24=More keys 
Flexible Character String Search with OPNQRYF

Figure 3 The CRTSSETF Command Source

 /*===================================================================*/ /* To compile: */ /* CRTCMD CMD(XXX/CRTSSETF) PGM(XXX/SSET001CL) + */ /* SRCFILE(XXX/QCMDSRC) */ /* */ /*===================================================================*/ CRTSSETF: CMD PROMPT('Create Subset of File') PARM KWD(PF) TYPE(Q1) MIN(1) PROMPT('File' 1) PARM KWD(CHRFIELD) TYPE(*NAME) LEN(10) MIN(1) + PROMPT('Character field to search' 2) PARM KWD(SEARCHSTR) TYPE(*CHAR) LEN(25) MIN(1) + EXPR(*YES) PROMPT('Search string' 4) PARM KWD(TRANSLATE) TYPE(*CHAR) LEN(4) RSTD(*YES) + DFT(*YES) VALUES(*YES *NO) + PROMPT('Translate field to uppercase' 3) PARM KWD(SNGWLDCRD) TYPE(*CHAR) LEN(1) DFT('_') + PROMPT('Single character wild card' 5) PARM KWD(SSTWLDCRD) TYPE(*CHAR) LEN(1) DFT('*') + PROMPT('Substring wild card' 6) PARM KWD(OUTFILE) TYPE(Q2) PROMPT('Outfile' 7) PARM KWD(CRTF) TYPE(*CHAR) LEN(4) RSTD(*YES) + DFT(*YES) VALUES(*YES *NO) PROMPT('Create + file' 8) PARM KWD(MBR) TYPE(*NAME) LEN(10) DFT(*FIRST) + SPCVAL((*FIRST)) PROMPT('Member' 9) PARM KWD(MBROPT) TYPE(*CHAR) LEN(8) RSTD(*YES) + DFT(*REPLACE) VALUES(*ADD *REPLACE) + PMTCTL(PMTCTL1) PROMPT('Member option' 10) PMTCTL1: PMTCTL CTL(CRTF) COND((*EQ '*NO')) Q1: QUAL TYPE(*NAME) LEN(10) QUAL TYPE(*NAME) LEN(10) DFT(*LIBL) + SPCVAL((*LIBL)) PROMPT('Library') Q2: QUAL TYPE(*NAME) LEN(10) QUAL TYPE(*NAME) LEN(10) DFT(QTEMP) + PROMPT('Library') 
Flexible Character String Search with OPNQRYF

Figure 4 CPP SSET001CL Source

 /*==================================================================*/ /* To compile: */ /* */ /* CRTCLPGM PGM(XXX/SSET001CL) SRCFILE(XXX/QCLSRC) */ /* */ /*==================================================================*/ SSET001CL: + PGM PARM(&QPF &CHRFIELD &SEARCHSTR &TRANSLATE &SNGWLDCRD + &SSTWLDCRD &QOF &CRTF &OFMBR &ADDREPL) DCL VAR(&CLEANED_UP) TYPE(*LGL) LEN(1) VALUE('0') DCL VAR(&NORMAL) TYPE(*LGL) LEN(1) VALUE('0') DCL VAR(&ERRORSW) TYPE(*LGL) LEN(1) DCL VAR(&MSGID) TYPE(*CHAR) LEN(7) DCL VAR(&MSGDTA) TYPE(*CHAR) LEN(256) DCL VAR(&MSGF) TYPE(*CHAR) LEN(10) DCL VAR(&MSGFLIB) TYPE(*CHAR) LEN(10) DCL VAR(&ADDREPL) TYPE(*CHAR) LEN(8) DCL VAR(&CHRFIELD) TYPE(*CHAR) LEN(10) DCL VAR(&CRTF) TYPE(*CHAR) LEN(4) DCL VAR(&DBLQTE) TYPE(*CHAR) LEN(1) VALUE('"') DCL VAR(&OF) TYPE(*CHAR) LEN(10) DCL VAR(&OFLIB) TYPE(*CHAR) LEN(10) DCL VAR(&OFMBR) TYPE(*CHAR) LEN(10) DCL VAR(&PF) TYPE(*CHAR) LEN(10) DCL VAR(&PFLIB) TYPE(*CHAR) LEN(10) DCL VAR(&QOF) TYPE(*CHAR) LEN(20) DCL VAR(&QPF) TYPE(*CHAR) LEN(20) DCL VAR(&QRYSLT) TYPE(*CHAR) LEN(80) DCL VAR(&SEARCHSTR) TYPE(*CHAR) LEN(25) DCL VAR(&SNGWLDCRD) TYPE(*CHAR) LEN(1) DCL VAR(&SSTWLDCRD) TYPE(*CHAR) LEN(1) DCL VAR(&TRANSLATE) TYPE(*CHAR) LEN(4) DCL VAR(&WLDCRDS) TYPE(*CHAR) LEN(2) MONMSG MSGID(CPF0000) EXEC(GOTO CMDLBL(ERRPROC)) CHGVAR VAR(&WLDCRDS) VALUE(&SNGWLDCRD *CAT &SSTWLDCRD) CHGVAR VAR(&PF) VALUE(%SST(&QPF 1 10)) CHGVAR VAR(&PFLIB) VALUE(%SST(&QPF 11 10)) CHGVAR VAR(&OF) VALUE(%SST(&QOF 1 10)) CHGVAR VAR(&OFLIB) VALUE(%SST(&QOF 11 10)) IF COND(&TRANSLATE *EQ '*YES') THEN(CHGVAR VAR(&QRYSLT) + VALUE('%XLATE(' *TCAT &CHRFIELD *BCAT 'QSYSTRNTBL)' *BCAT + '*EQ %WLDCRD(')) ELSE CMD(CHGVAR VAR(&QRYSLT) VALUE(&CHRFIELD *BCAT '*EQ %WLDCRD(')) CHGVAR VAR(&QRYSLT) VALUE(&QRYSLT *TCAT &DBLQTE *TCAT &SEARCHSTR + *TCAT &DBLQTE *BCAT &DBLQTE *TCAT &WLDCRDS *TCAT &DBLQTE + *TCAT ')') IF COND(&CRTF *EQ '*NO') THEN(DO) CHKOBJ OBJ(&OFLIB/&OF) OBJTYPE(*FILE) MBR(&OFMBR) MONMSG MSGID(CPF9800) EXEC(DO) SNDPGMMSG MSGID(CPF9898) MSGF(QCPFMSG) MSGDTA('Outfile' + *BCAT &OF *BCAT 'Member' *BCAT &OFMBR *BCAT 'in + library' *BCAT &OFLIB *BCAT 'does not exist') + MSGTYPE(*ESCAPE) ENDDO ENDDO ELSE CMD(DO) CHKOBJ OBJ(&OFLIB/&OF) OBJTYPE(*FILE) MBR(&OFMBR) MONMSG MSGID(CPF9800) EXEC(GOTO CMDLBL(SKIP)) SNDPGMMSG MSGID(CPF9898) MSGF(QCPFMSG) MSGDTA('Outfile' *BCAT + &OF *BCAT 'in library' *BCAT &OFLIB *BCAT 'already + exists') MSGTYPE(*ESCAPE) SKIP: + ENDDO OVRDBF FILE(&PF) SHARE(*YES) OPNQRYF FILE((&PFLIB/&PF)) QRYSLT(&QRYSLT) CPYFRMQRYF FROMOPNID(&PF) TOFILE(&OFLIB/&OF) TOMBR(&OFMBR) + MBROPT(&ADDREPL) CRTFILE(&CRTF) NORMAL_END: + CHGVAR VAR(&NORMAL) VALUE('1') CLEAN_UP: + CHGVAR VAR(&CLEANED_UP) VALUE('1') CLOF OPNID(&PF) DLTOVR FILE(&PF) IF COND(&NORMAL) THEN(RETURN) ERRPROC: + IF COND(*NOT &CLEANED_UP) THEN(GOTO CMDLBL(CLEAN_UP)) IF COND(&ERRORSW) THEN(SNDPGMMSG MSGID(CPF9999) MSGF(QCPFMSG) + MSGTYPE(*ESCAPE)) ELSE CMD(CHGVAR VAR(&ERRORSW) VALUE('1')) ERRLOOP: + RCVMSG MSGTYPE(*DIAG) MSGDTA(&MSGDTA) MSGID(&MSGID) MSGF(&MSGF) + MSGFLIB(&MSGFLIB) IF COND(&MSGID *EQ ' ') THEN(GOTO CMDLBL(ERRDONE)) SNDPGMMSG MSGID(&MSGID) MSGF(&MSGFLIB/&MSGF) MSGDTA(&MSGDTA) + MSGTYPE(*DIAG) GOTO CMDLBL(ERRLOOP) ERRDONE: + RCVMSG MSGTYPE(*EXCP) MSGDTA(&MSGDTA) MSGID(&MSGID) MSGF(&MSGF) + MSGFLIB(&MSGFLIB) SNDPGMMSG MSGID(&MSGID) MSGF(&MSGFLIB/&MSGF) MSGDTA(&MSGDTA) + MSGTYPE(*ESCAPE) ENDPGM: + ENDPGM 
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: