COBOL REWRITE for VSAM

REWRITE persists the contents of the current record buffer back to the VSAM dataset for the logical record you already positioned with READ. For KSDS maintenance programs, REWRITE is the workhorse of change-of-address, status code flip, and balance adjustment transactions that do not alter primary keys. This page documents the read-modify-write rhythm, explains why OPEN I-O is mandatory, discusses record length constraints for fixed versus variable files, and lists failure modes such as attempting REWRITE after a failed READ or clobbering the key field accidentally while editing the payload. The tone stays practical because REWRITE bugs become production incidents when two programs update the same cluster without serialization.

Standard update flow

Read-for-update pipeline
StepPurpose
OPEN I-OObtain update-capable control blocks.
READ for updateBring current record into buffer; establish VSAM position.
Validate business rulesChange payload fields allowed by spec.
REWRITEPersist buffer to the same logical record.
Check FILE STATUSBranch on failure; consider rollback semantics if part of larger transaction.

Code sketch

cobol
1
2
3
4
5
6
7
8
9
10
11
READ CUSTFILE END-READ IF WS-FS NOT = '00' GO TO READ-ERROR-EXIT END-IF MOVE NEW-EMAIL TO CUST-EMAIL REWRITE CUST-RECORD END-REWRITE IF WS-FS NOT = '00' PERFORM REWRITE-FAILED END-IF

Some shops wrap READ and REWRITE in atomic paragraphs that log before-image and after-image columns for audit tables. VSAM itself does not give you SQL transactions; coordination with DB2 or logging queues is a separate architecture topic. At minimum, capture FILE STATUS on both verbs so night support can tell whether the failure happened before or after your business edits touched the buffer.

Length and layout rules

  • Fixed-length records: REWRITE must preserve overall length; padding fields should use explicit spaces or zeros per standards.
  • Variable-length: respect FD DEPENDING ON source; changing length may be allowed up to maximum defined in catalog RECORDSIZE.
  • Never let group moves overlay key fields unless the specification explicitly allows key rotation via delete-insert elsewhere.

Concurrency reality

Two batch jobs updating the same record without locking can interleave READ/REWRITE pairs in surprising orders. SHAREOPTIONS and application-level enqueue protocols decide whether VSAM blocks, fails, or allows the interleaving. When converting QSAM-style “last writer wins” thinking to VSAM, revisit concurrency design instead of copying patterns blindly.

When REWRITE is the wrong tool

If the business operation truly adds a second row with a new key, use WRITE. If the business retires a row, use DELETE (when supported) or logical delete flags per design. If the business replaces every field including identifiers, consider whether the operation is modeled as insert of a new cluster row versus update; data modeling workshops settle this better than hallway decisions minutes before code freeze.

Testing REWRITE safely

Build a clone cluster with identical attributes but a different name for destructive testing. Copy a subset of production-shaped rows with REPRO, run your REWRITE program against the clone, then diff outputs with SORT or file comparison utilities approved by your shop. Never first-test REWRITE logic on shared production masters even when “the change looks tiny.” Regression suites should include at least one wide record, one narrow record, and one variable-length edge case if your FD allows variable length.

Audit columns and REWRITE

Many applications maintain LAST-UPDATED-TIMESTAMP and LAST-UPDATED-BY columns inside the VSAM record itself. Ensure those fields update on every successful REWRITE path, not only on INSERT paths, or auditors will infer stale records are untouched when they were actually corrected without traceability. Pair VSAM updates with application log tables when regulations require immutable history beyond the current record image.

Variable-length REWRITE pitfalls

When DEPENDING ON controls payload length, changing only the payload without updating the depending item leaves VSAM with inconsistent length metadata in the buffer. Always move the new length into the depending item before REWRITE when the record grew or shrank within allowed maximum. Failing to do so produces length errors that look like random corruption because half the downstream consumers read stale bytes past the new logical end. Unit tests should include shrink and grow cases, not only fixed-length edits.

Idempotency expectations

Modern interfaces sometimes retry the same financial adjustment twice. If your REWRITE path is not idempotent—perhaps it increments a counter every time—duplicate retries double-count. Design REWRITE handlers so repeated application of the same business message leaves the record in the same final state, or store a processed-message identifier inside the row to reject duplicates. This is not a VSAM feature; it is application discipline that surfaces first during REWRITE-heavy workloads because updates touch fewer validation layers than inserts.

Hands-on exercises

  1. Implement read-modify-write on a sandbox KSDS and log WS-FS after each verb.
  2. Attempt REWRITE without READ in a throwaway program and record the FILE STATUS your environment returns.
  3. Pair with a peer to review whether your program ever moves data into the primary key field by mistake during group MOVEs.

Explain Like I'm Five

REWRITE is tracing over words in a workbook page with a pencil after you already opened to that page. If you never opened the book to the page, you cannot trace. If you try to tear the page out and slip in a brand new page with a new title, that is not tracing—that is WRITE or delete-insert. Keep the same page number and same title; only change the doodles in the boxes you are allowed to change.

Test Your Knowledge

Test Your Knowledge

1. Which OPEN mode is required for REWRITE on a KSDS?

  • INPUT
  • OUTPUT
  • I-O
  • EXTEND only

2. REWRITE replaces the record that:

  • Has any key in the file
  • Was most recently read into the buffer for that file with correct positioning
  • Sorted last alphabetically
  • Lives in SYSOUT

3. Using WRITE instead of REWRITE to change an existing key's payload usually:

  • Is always correct
  • Risks duplicate key or wrong semantics
  • Improves CI size
  • Skips catalog lookup
Published
Read time10 min
AuthorMainframeMaster
Reviewed by MainframeMaster teamVerified: IBM Enterprise COBOL Language ReferenceSources: IBM Enterprise COBOL for z/OS Language ReferenceApplies to: z/OS 2.5 / 3.x