💻 COBOL
COBOL DELETE Statement
Intermediate 🕑 10 min read
👁 0 views
COBOL DELETE Statement
The DELETE statement removes a record from an indexed or relative file.
Syntax
DELETE file-name RECORD
[INVALID KEY imperative-statement]
[NOT INVALID KEY imperative-statement]
[END-DELETE]
Example Program
IDENTIFICATION DIVISION.
PROGRAM-ID. DELETE-DEMO.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'EMPLOYEE.DAT'
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS EMP-ID
FILE STATUS IS WS-FILE-STATUS.
DATA DIVISION.
FILE SECTION.
FD EMP-FILE.
01 EMP-RECORD.
05 EMP-ID PIC 9(5).
05 EMP-NAME PIC X(30).
05 EMP-SALARY PIC 9(7)V99.
WORKING-STORAGE SECTION.
01 WS-FILE-STATUS PIC XX.
01 WS-DELETE-ID PIC 9(5).
PROCEDURE DIVISION.
OPEN I-O EMP-FILE
IF WS-FILE-STATUS NOT = '00'
DISPLAY 'Error opening file'
STOP RUN
END-IF
* Set the key of record to delete
MOVE 00003 TO EMP-ID
* For random access, READ is optional before DELETE
* For sequential access, READ is required
DELETE EMP-FILE RECORD
INVALID KEY
DISPLAY 'Record ' EMP-ID ' not found'
NOT INVALID KEY
DISPLAY 'Record ' EMP-ID ' deleted'
END-DELETE
CLOSE EMP-FILE
STOP RUN.
Expected Output
Record 00003 deleted
(or "Record 00003 not found" if record doesn't exist)
Key Points
- File must be opened I-O
- For sequential access, READ before DELETE
- For random access, just set the key
- Only for indexed and relative files
- Cannot DELETE from sequential files