Direct answer: For most COBOL indexed‑file implementations, using a WRITE followed by a check of File Status 22 is the simpler and usually faster way to achieve idempotent writes; REWRITE only adds an extra write on the first attempt and does not give a measurable performance benefit unless you already know the record exists.
Confirmed Facts
- A
WRITE that returns File Status 22 indicates a duplicate key; the status check adds negligible overhead compared to the disk I/O of the write itself. - Using
REWRITE assumes the record already exists; the first attempt must create the record with a WRITE, and subsequent retries simply overwrite the same key. - Performance‑wise, the extra status check after
WRITE is usually equal to or faster than doing an initial WRITE plus repeated REWRITE when duplicates are rare. - After a failed
WRITE due to a duplicate key, the COBOL runtime leaves the file pointer unchanged, allowing a following REWRITE (or another WRITE) to target the same key without an explicit reposition.
Likely Explanation
The WRITE‑with‑check pattern avoids the extra write needed to create a record before you can REWRITE it. When the chance of a duplicate is low, you pay only the cost of one write and a cheap status test. The REWRITE pattern is useful only when you can guarantee the record exists (e.g., after an initial WRITE) and you want to eliminate the status test; however, you still incur the initial write, so there is no net gain unless your environment makes the status test unusually expensive.
Steps for This Case
- Open the indexed file in I‑O mode.
- Attempt a
WRITE of the record with the unique key. - Check
FILE‑STATUS: - If it equals
"00", the write succeeded. - If it equals
"22", treat the operation as a no‑op (the record already exists). - Any other status indicates a real error and should be handled according to your error‑handling policy.
- Close the file.
If you prefer the REWRITE approach:
- Open the file in I‑O mode.
- Perform an initial
WRITE to create the record (ignore status 22 on this first attempt, or handle it as an error if the record should not exist yet). - On each retry, issue a
REWRITE using the same key; the runtime will overwrite the existing record. - Check
FILE‑STATUS after each REWRITE for errors other than "00". - Close the file.
To confirm which approach is safest for your specific compiler, please tell me which COBOL runtime (e.g., IBM Enterprise COBOL, Micro Focus Visual COBOL, GnuCOBOL) you are targeting, as some implementations may reset the file pointer or return a non‑22 status on a duplicate‑key WRITE.