COBOL - Tratamento de arquivos VSAM - ESDS KSDS RRDS
Use a instrução CLOSE para desconectar seu programa do arquivo VSAM. Se você tentar fechar um arquivo que já está fechado, obterá um erro lógico. Você deve verificar a chave de status do arquivo após cada instrução CLOSE.
Caso você não feche um arquivo VSAM, o COBOL fechará automaticamente o arquivo para você, fornecendo uma mensagem de diagnóstico de nível de aviso. Consulte os detalhes de "Fechamento automático de arquivos".
Use the CLOSE statement to disconnect your program from the VSAM file. If you try to close a file that is already closed, you will get a logic error. You should check the file status key after each CLOSE statement.
In the event that you do not close a VSAM file, COBOL will automatically close the file for you, giving you a warning-level diagnostic message. See "Automatic Closing of Files" details.
Abra o arquivo para IO e use a instrução DELETE para remover um registro existente em um arquivo indexado ou relativo. Você não pode usar DELETE em um arquivo sequencial.
Quando o ACESSO É SEQUENCIAL, ou se o arquivo contém registros estendidos, o registro a ser excluído deve primeiro ser lido pelo programa COBOL. O DELETE então remove o registro que foi lido. Se DELETE não for precedido por uma READ bem-sucedida, a exclusão não é feita e o valor da chave de status é definido como 92.
Quando o ACESSO É RANDOM ou O ACESSO É DINÂMICO, e se os registros não são estendidos, o registro a ser excluído não precisa ser lido pelo programa COBOL. Para excluir um registro, a chave do registro a ser excluído é movida para o item de dados RECORD KEY e o DELETE é emitido. Você deve verificar a chave de status do arquivo após cada instrução DELETE.
Open the file for I-O and use the DELETE statement to remove an existing record on an indexed or relative file. You cannot use DELETE on a sequential file.
When ACCESS IS SEQUENTIAL, or if the file contains spanned records, the record to be deleted must first be read by the COBOL program. The DELETE then removes the record that was read. If the DELETE is not preceded by a successful READ, the deletion is not done and the status key value is set to 92.
When ACCESS IS RANDOM or ACCESS IS DYNAMIC, and if the records are not spanned, the record to be deleted need not be read by the COBOL program. To delete a record, the key of the record to be deleted is moved to the RECORD KEY data item and the DELETE is issued. You should check the file status key after each DELETE statement.
Para substituir registros em um arquivo VSAM, use REWRITE em um arquivo que você abriu para IO. Se você tentar usar REWRITE em um arquivo que não está aberto IO, o registro não será regravado e a chave de status será definida como 49. Você deve verificar a chave de status do arquivo após cada instrução REWRITE.
Para substituir registros aleatoriamente ou dinamicamente, o registro a ser regravado não precisa ser lido pelo programa COBOL. Em vez disso, para posicionar o registro que deseja atualizar:
To replace records in a VSAM file, use REWRITE in a file that you have opened for I-O. If you attempt to use REWRITE on a file that is not opened I-O, the record is not rewritten and the status key is set to 49. You should check the file status key after each REWRITE statement.
To replace records randomly or dynamically, the record to be rewritten need not be read by the COBOL program. Instead, to position the record you want to update:
A instrução COBOL WRITE adiciona um registro a um arquivo, sem substituir nenhum registro existente. O registro a ser adicionado não deve ser maior que o tamanho máximo do registro especificado quando o arquivo foi definido. Você deve verificar a chave de status do arquivo após cada instrução WRITE.
Use ACCESS IS SEQUENTIAL e codifique a instrução WRITE para adicionar registros sequencialmente ao final de um arquivo VSAM que foi aberto com OUTPUT ou EXTEND. Os arquivos sequenciais são sempre gravados sequencialmente.
Para arquivos indexados, os novos registros devem ser gravados em sequência de teclas ascendente. Se o arquivo EXTEND for aberto, as chaves de registro dos registros a serem adicionados devem ser maiores do que a chave de registro primária mais alta do arquivo quando o arquivo foi aberto.
Para arquivos relativos, os registros devem estar em sequência. Se você incluir um item de dados RELATIVE KEY na cláusula SELECT, o número de registro relativo do registro recém-escrito é colocado nesse item de dados.
Quando você grava registros em um conjunto de dados indexados e ACCESS IS RANDOM ou ACCESS IS DYNAMIC, os registros podem ser gravados em qualquer ordem.
The COBOL WRITE statement adds a record to a file, without replacing any existing records. The record to be added must not be larger than the maximum record size specified when the file was defined. You should check the file status key after each WRITE statement.
Adding Records Sequentially
Use ACCESS IS SEQUENTIAL and code the WRITE statement to add records sequentially to the end of a VSAM file that has been opened with either OUTPUT or EXTEND. Sequential files are always written sequentially.
For indexed files, new records must be written in ascending key sequence. If the file is opened EXTEND, the record keys of the records to be added must be higher than the highest primary record key on the file when the file was opened.
For relative files, the records must be in sequence. If you include a RELATIVE KEY data-item in the SELECT clause, the relative record number of the record just written is placed in that data item.
When you write records to an indexed data set and ACCESS IS RANDOM or ACCESS IS DYNAMIC, the records can be written in any order.
As instruções de linguagem COBOL que podem ser usadas para atualizar um arquivo VSAM nas Divisões de Ambiente e Dados são as mesmas.
A Figura mostra as instruções que você pode usar na Divisão de Procedimento para atualizar arquivos VSAM.
The COBOL language statements that can be used to update a VSAM file in the Environment and Data Divisions are the same.
Figure shows the statements that you can use in the Procedure Division to update VSAM files.
ACCESS IS SEQUENTIAL: OPEN EXTEND WRITE CLOSE OR OPEN I-O READ REWRITE CLOSE
ACCESS IS SEQUENTIAL: OPEN EXTEND WRITE CLOSE OR OPEN I-O READ REWRITE DELETE CLOSE
ACCESS IS RANDOM: NOT APPLICABLE
ACCESS IS RANDOM: OPEN I-O READ WRITE REWRITE DELETE CLOSE
ACCESS IS DYNAMIC: Sequential Processing NOT APPLICABLE
ACCESS IS DYNAMIC: Sequential Processing OPEN I-O READ NEXT WRITE REWRITE START DELETE CLOSE
ACCESS IS DYNAMIC: Random Processing NOT APPLICABLE
ACCESS IS DYNAMIC: Random Processing OPEN I-O READ WRITE REWRITE DELETE CLOSE
Use a instrução READ para recuperar (READ) registros de um arquivo. Para ler um registro, você deve ter aberto o arquivo INPUT ou IO. Você deve verificar a chave de status do arquivo após cada instrução READ.
Os registros em arquivos sequenciais VSAM podem ser recuperados apenas na sequência em que foram gravados.
Registros em arquivos indexados e relativos de VSAM podem ser recuperados:
Com o acesso dinâmico, você pode alternar entre ler um registro específico diretamente e ler registros sequencialmente, usando READ NEXT para recuperação sequencial e READ para recuperação aleatória (por chave). Consulte "Modos de acesso a arquivos" para obter uma descrição completa dos recursos de cada modo de acesso.
Quando você quiser ler sequencialmente, começando em um registro específico, use START antes de READ NEXT para definir o indicador de posição do arquivo para apontar para um registro específico. Quando você especifica START seguido por READ NEXT, o próximo registro é lido e o indicador de posição do arquivo é redefinido para o próximo registro. O indicador de posição do arquivo pode ser movido aleatoriamente com o uso de START, mas todas as leituras são feitas sequencialmente a partir desse ponto. Você pode continuar a ler registros sequencialmente ou pode usar a instrução START para mover o indicador de posição do arquivo:
START file-name KEY IS EQUAL TO ALTERNATE-RECORD-KEY
Quando um READ direto é executado, com base em um índice alternativo para o qual existem duplicatas, apenas o primeiro registro no conjunto de dados (cluster de base) com esse valor de chave alternativa é recuperado. Você precisa de uma série de instruções READ NEXT para recuperar cada um dos registros do conjunto de dados com a mesma chave alternativa. Um valor FILE STATUS de '02' é retornado se houver mais registros com o mesmo valor de chave alternativa para serem lidos; um valor de '00' é retornado quando o último registro com aquele valor de chave foi lido.
Use the READ statement to retrieve (READ) records from a file. To read a record, you must have opened the file INPUT or I-O. You should check the file status key after each READ statement.
Records in VSAM sequential files can be retrieved only in the sequence in which they were written.
Records in VSAM indexed and relative files can be retrieved:
With dynamic access, you can switch between reading a specific record directly and reading records sequentially, by using READ NEXT for sequential retrieval and READ for random retrieval (by key). See "File Access Modes" for a complete description of the features of each access mode.
When you want to read sequentially, beginning at a specific record, use START before the READ NEXT to set the file position indicator to point to a particular record. When you specify START followed by READ NEXT, the next record is read and the file position indicator is reset to the next record. The file position indicator can be moved around randomly through the use of START, but all reading is done sequentially from that point. You can continue to read records sequentially, or you can use the START statement to move the file position indicator:
When a direct READ is executed, based on an alternate index for which duplicates exist, only the first record in the data set (base cluster) with that alternate key value is retrieved. You need a series of READ NEXT statements to retrieve each of the data set records with the same alternate key. A FILE STATUS value of '02' is returned if there are more records with the same alternate key value to be read; a value of '00' is returned when the last record with that key value has been read.
Como você codifica sua instrução OPEN para um arquivo VSAM depende se o arquivo é um arquivo vazio ou um arquivo carregado.
Para abrir um arquivo que nunca conteve registros (um arquivo vazio):
Use OPEN OUTPUT para arquivos ESDS.
Para abrir um arquivo que já contém registros (um arquivo carregado):
Use OPEN INPUT, OPEN I-O ou OPEN EXTEND
Um arquivo que antes continha registros, todos os quais foram excluídos, pode ser aberto como I-O ou EXTEND.
Em todos os casos, você deve verificar a chave de status do arquivo após cada instrução OPEN.
Subtópicos:
Carregando um conjunto de dados VSAM com serviços de método de acesso
How you code your OPEN statement for a VSAM file depends on whether the file is an empty file or a loaded file.
To open a file that has never contained records (an empty file):
Use OPEN OUTPUT for ESDS files.
To open a file that already contains records (a loaded file):
Use OPEN INPUT, OPEN I-O, or OPEN EXTEND
A file that once contained records, all of which have been deleted, can be opened as I-O or EXTEND.
In every case, you should check the file status key after each OPEN statement.
Subtopics:
Loading a VSAM Data Set with Access Method Services
O indicador de posição do arquivo indica o próximo registro a ser acessado para solicitações COBOL sequenciais. Você não especifica o indicador de posição do arquivo em nenhum lugar do programa. O indicador de posição do arquivo é definido por instruções OPEN, START, READ e READ NEXT bem-sucedidas. As solicitações READ ou READ NEXT subsequentes usam a posição do indicador de posição do arquivo estabelecida e atualiza-a.
O indicador de posição do arquivo não é usado ou afetado pelas instruções de saída WRITE, REWRITE ou DELETE. O indicador de posição do arquivo não tem significado para processamento aleatório.
The file position indicator indicates the next record to be accessed for sequential COBOL requests. You do not specify the file position indicator anywhere in your program. The file position indicator is set by successful OPEN, START, READ, and READ NEXT statements. Subsequent READ or READ NEXT requests then use the established file position indicator position and update it.
The file position indicator is not used or affected by the output statements WRITE, REWRITE, or DELETE. The file position indicator has no meaning for random processing.
Todos os erros no processamento de um arquivo VSAM, sejam erros de lógica em seu programa ou erros de E/S na mídia de armazenamento externa, retornam o controle para seu programa COBOL. Quando ocorrer um erro, o valor da chave de status indicará o status da última solicitação no arquivo. Consulte a Referência da Linguagem de Programação de Aplicativo VS COBOL II se precisar saber os valores da chave de status e seus significados para arquivos VSAM. Como os problemas de arquivo geralmente não causam um abend, é possível que seu programa continue executando com informações inválidas. A boa prática de codificação exige que você verifique o valor da chave de status do arquivo após cada solicitação de entrada/saída (incluindo OPEN e CLOSE). Cada arquivo VSAM deve ter sua própria chave de status definida em seu programa. Para obter mais informações, consulte "Chave de status do arquivo" no tópico 4.4.3.
Você também pode usar um ERROR/EXCEPTION declarativo para lidar com erros de entrada/saída para arquivos VSAM
All errors in processing a VSAM file, whether logic errors in your program or I/O errors on the external storage media, return control to your COBOL program. When an error occurs, the status key value will indicate the status of the last request on the file. Refer to VS COBOL II Application Programming Language Reference if you need to know the status key values and their meanings for VSAM files. Because file problems do not usually cause an abend, it is possible that your program will continue executing with invalid information. Good coding practice demands that you check the file status key value after every input/output request (including OPEN and CLOSE). Each VSAM file should have its own status key defined in your program. For more information, see "File Status Key" in topic 4.4.3.
You can also use an ERROR/EXCEPTION declarative for handling input/output errors for VSAM files
O processamento do arquivo VSAM envolve sete instruções COBOL:
Todos os itens a seguir determinam quais instruções de entrada/saída são válidas para um determinado conjunto de dados VSAM:
A figura mostra as combinações possíveis com arquivos sequenciais (ESDS). O 'X' indica que a instrução especificada pode ser usada com o modo aberto fornecido no topo da coluna.
VSAM file processing involves seven COBOL statements:
All of the following determine which input/output statements are valid for a given VSAM data set:
Fgure shows the possible combinations with sequential files (ESDS). The 'X' indicates that the specified statement may be used with the open mode given at the top of the column.
A figura mostra as combinações possíveis com arquivos indexados (KSDS) e relativos (RRDS). O 'X' indica que a instrução especificada pode ser usada com o modo aberto fornecido no topo da coluna.
Figure shows the possible combinations with indexed (KSDS) and relative (RRDS) files. The 'X' indicates that the specified statement may be used with the open mode given at the top of the column.
Você só pode acessar registros em arquivos sequenciais VSAM sequencialmente. Você pode acessar registros em arquivos indexados e relativos do VSAM de três maneiras: sequencialmente, aleatoriamente ou dinamicamente.
Acesso sequencial - especifique ACCESS IS SEQUENTIAL na entrada FILE-CONTROL. Para arquivos indexados, os registros são acessados na ordem do campo-chave selecionado (primário ou alternativo). Para arquivos relativos, os registros são acessados na ordem dos números dos registros relativos.
Acesso aleatório - especifique ACCESS IS RANDOM na entrada FILE-CONTROL. Para arquivos indexados, os registros são acessados de acordo com o valor que você coloca em um campo-chave. Para arquivos relativos, os registros são acessados de acordo com o valor que você coloca na chave relativa.
Acesso dinâmico - especifique ACCESS IS DYNAMIC na entrada FILE-CONTROL.
O acesso dinâmico é um acesso sequencial-aleatório misto dentro do mesmo programa. Usando o acesso dinâmico, você pode escrever um programa para executar o processamento sequencial e aleatório, acessando alguns registros em ordem sequencial e outros por suas chaves.
Por exemplo, suponha que você tenha um arquivo indexado de registros de funcionários e o salário por hora do funcionário forme a chave do registro. Além disso, suponha que seu programa esteja interessado nos funcionários que ganham entre US $ 7,00 e US $ 9,00 por hora e aqueles que ganham US $ 15,00 por hora e acima. Para fazer isso, recupere o primeiro registro aleatoriamente (com uma recuperação aleatória READ) com base na chave de 0700. Em seguida, comece a ler sequencialmente (ou seja, usando READ NEXT) até que o campo de salário exceda 0900. Você então voltaria para uma leitura aleatória, desta vez com base em uma chave de 1500. Após essa leitura aleatória, volte a ler sequencialmente até chegar ao final do arquivo.
You can only access records in VSAM sequential files sequentially. You can access records in VSAM indexed and relative files in three ways: sequentially, randomly, or dynamically.
Sequential access - Specify ACCESS IS SEQUENTIAL in the FILE-CONTROL entry. For indexed files, records are accessed in the order of the key field selected (either primary or alternate). For relative files, records are accessed in the order of the relative record numbers.
Random access - Specify ACCESS IS RANDOM in the FILE-CONTROL entry. For indexed files, records are accessed according to the value you place in a key field. For relative files, records are accessed according to the value you place in the relative key.
Dynamic access - Specify ACCESS IS DYNAMIC in the FILE-CONTROL entry.
Dynamic access is a mixed sequential-random access within the same program. Using dynamic access, you can write one program to perform both sequential and random processing, accessing some records in sequential order and others by their keys.
For example, suppose you had an indexed file of employee records, and the employee's hourly wage formed the record key. Also, suppose your program was interested in those employees earning between $7.00 and $9.00 per hour and those earning $15.00 per hour and above. To do this, retrieve the first record randomly (with a random-retrieval READ) based on the key of 0700. Next, begin reading sequentially (that is, using READ NEXT) until the salary field exceeds 0900. You would then switch back to a random read, this time based on a key of 1500. After this random read, switch back to reading sequentially until you reach the end of the file.
A organização física dos conjuntos de dados VSAM difere consideravelmente das usadas por outros métodos de acesso. Os conjuntos de dados VSAM são mantidos em intervalos de controle e áreas de controle; o tamanho deles é normalmente determinado pelo método de acesso e a maneira como são usados não é visível para você. Existem três tipos de organização de arquivos que você pode usar com VSAM
Nota: Ao longo deste livro, o termo conjunto de dados de registro relativo VSAM (ou RRDS) é usado para significar ambos os conjuntos de dados de registro relativo com registros de comprimento fixo e com registros de comprimento variável, a menos que eles precisem ser diferenciados.
Para todo o processamento do conjunto de dados VSAM, você pode usar formatos de registro de comprimento fixo ou variável sem qualquer codificação especial. Se você não puder ou optar por não usar RRDS de comprimento variável VSAM, poderá usar "conjuntos de dados relativos de comprimento variável simulado COBOL." Para obter informações sobre o uso de conjuntos de dados relativos de comprimento variável simulado, consulte o Apêndice C, "Processando RRDS de comprimento variável simulado".
The physical organization of VSAM data sets differs considerably from those used by other access methods. VSAM data sets are held in control intervals and control areas; the size of these is normally determined by the access method, and the way in which they are used is not visible to you. There are three types of file organization you can use with VSAM
Note: Throughout this book, the term VSAM relative-record data set (or RRDS) is used to mean both relative-record data sets with fixed-length records and with variable-length records, unless they need to be differentiated.
For all VSAM data set processing, you can use either fixed or variable-length record formats without any special coding. If you cannot or choose not to use VSAM variable-length RRDS, you can use "COBOL simulated variable-length relative data sets." For information on using simulated variable-length relative data sets, see Appendix C, "Processing Simulated Variable-Length RRDS".