I am attempting to export the employee names in table employees into a flat file. The flat file should have the following structure:
HEADER
DETAILS JACK
DETAILS JUNE
TRAILER
What I am struggling with is to how I can run this in a loop to store the names in single rows in the same file. My current script is only exporting one name at a time into separate files. Since the filename remains the same, the files are overwriting each time the procedure is executed.
Please note that I wish to have filename as a variable if possible.
Create table Employees (Id number(10),Name varchar(40))
Insert into Employees values (1,'JOHN');
Insert into Employees values (2,'JACK');
Insert into Employees values (3,'JUNE');
-----------------------
CREATE OR REPLACE Procedure PRINT_NAMES(aId in Employees.Id%Type,
aFileName in varchar2)
Is
fDirectory varchar(30) := 'SB1KK_TEMP';
fName Employees.name%Type;
pFile Utl_File.file_type;
fLine Varchar2(1024);
Begin
pFile := UTL_FILE.fopen(fDirectory, aFileName, 'w');
--File Header
fLine := RPAD('HEADER', 10) || To_char(trunc(sysdate), 'yyyymmdd') || '000000';
UTL_FILE.put_line(pFile, convert(fLine, 'WE8ISO8859P1', 'UTF8'));
--File Details - This Section must be run in a loop
Select Name into fName From Employees where id = aId;
fLine := RPAD('DETAILS', 10) || RPAD(' ', 50) ||
To_char(trunc(sysdate), 'yyyymmdd') || RPAD(fName, 11);
UTL_FILE.put_line(pFile, convert(fLine, 'WE8ISO8859P1', 'UTF8'));
--File Trailer
fLine := RPAD('TRAILER', 10) || To_char(trunc(sysdate), 'yyyymmdd') || '000000';
UTL_FILE.put_line(pFile, convert(fLine, 'WE8ISO8859P1', 'UTF8'));
UTL_FILE.fclose(pFile);
End;
/
The stored procedure is run in a loop. The file TMP_LOG.txt is created over and over for each person in table employees.
Begin
For IDS in (Select * From Employees Where id in (2,3))
Loop
PRINT_NAMES(aId => IDS.ID, aFileName => 'TMP_LOG.TXT');
End Loop;
End;