7 Jan 2014

Using UTL_FILE

-- UTL FILE
--STEP 1
 CONN SYS/ORACLE AS SYSDBA

--STEP 2
 -- MAKE A FOLDER AT ANY DRIVE, WE CREATE FOLDER ON DRIVE D NAMELY D:\B67_M
 -- MOVE TO FOLDER C:\app\admin\product\11.2.0\dbhome_1\database
 -- MAKE A BACKUP FOLDER AND COPY SPFILE.ORA IN BACKUP FOLDER

--STEP 3
 SHOW PARAMETER SPFILE
 SHOW PARAMETER UTL_FILE_DIR

--STEP 4
SQL> CREATE PFILE FROM SPFILE;

--STEP 5
 -- MOVE TO FOLDER  C:\APP\ADMIN\PRODUCT\11.2.0\DB HOME_1\DATABASE, MODIFY THE INITORCL.ORA FILE,
 -- ADD THE PARAMETER UTL_FILE_DIR = D:\B67_M
 -- AFTER ADDING THE PARAMETER RESTART THE DATABASE WITH FOLLOWING COMMAND

STARTUP FORCE PFILE=C:\app\admin\product\11.2.0\dbhome_1\database\initorcl.ora
show parameter utl_file_dir

--STEP 6
 -- CREATE SPFILE FROM PFILE
CREATE SPFILE FROM PFILE;

STARTUP FORCE;

-- SETP 7 CREATING DIRECTOY AND GIVE THE GRANT TO THE USER FOR ACCESS
CREATE DIRECTORY B67M AS 'D:\B67_M';
GRANT READ,WRITE ON DIRECTORY B67M TO SCOTT;

-- SETP 8  CREATING PROCEDURE OR FUNCTION TO UTLIZE DIRECTORY
conn scott/tiger

desc utl_file

CREATE OR REPLACE PROCEDURE WRITE_TO_FILE(DIR_NAME IN VARCHAR2 DEFAULT 'B67M',
   FILE_NAME IN VARCHAR2 DEFAULT 'EINFO.TXT') IS
   F1 UTL_FILE.FILE_TYPE;
   PRESENT BOOLEAN; FLENGTH NUMBER; BSIZE PLS_INTEGER;
   CURSOR C1 IS SELECT * FROM EMP ; CNTR NUMBER:=0;
BEGIN
  -- Checking the file exist in folder or not
  UTL_FILE.FGETATTR(LOCATION=>DIR_NAME,FILENAME=>FILE_NAME,
                    FEXISTS=>PRESENT,FILE_LENGTH=>FLENGTH,
                    BLOCK_SIZE=>BSIZE);
 -- Making Decision Open the file Write mode or Append mode
 IF PRESENT THEN
   F1:=UTL_FILE.FOPEN(DIR_NAME,FILE_NAME,'a');
   UTL_FILE.PUT_LINE(F1,RPAD('*',LENGTH(CURRENT_TIMESTAMP),'*'));
 ELSE
   F1:=UTL_FILE.FOPEN(DIR_NAME,FILE_NAME,'w');
   UTL_FILE.PUT_LINE(F1,RPAD('-',LENGTH(CURRENT_TIMESTAMP),'-'));
 END IF;
 FOR I IN C1 LOOP
  CNTR:=CNTR+1;
  UTL_FILE.PUT_LINE(F1,RPAD(CNTR,10,' ')||RPAD(I.EMPNO,10,' ')||RPAD(I.ENAME,10,' ')||RPAD(I.SAL,'10',' ')|| RPAD(I.DEPTNO,10,' '));
 END LOOP;
 DBMS_OUTPUT.PUT_LINE('FILE CREATED...'||FILE_NAME||' AS ON'||TO_CHAR(SYSDATE,'FMDAY')||','||CURRENT_TIMESTAMP);
 UTL_FILE.FCLOSE(F1);
EXCEPTION
 WHEN UTL_FILE.INVALID_FILEHANDLE THEN
  RAISE_APPLICATION_ERROR(-20001,' INVALID FILE MODE..');
 WHEN UTL_FILE.WRITE_ERROR THEN
  RAISE_APPLICATION_ERROR(-20010,'UNABLE TO WRITE DATA..');
 WHEN OTHERS THEN
  RAISE_APPLICATION_ERROR(-20420,SQLERRM);
END WRITE_TO_FILE;

DESC WRITE_TO_FILE

EXEC WRITE_TO_FILE(FILE_NAME=>'B67M_EMP.TXT');

-- FOR DISPLAYING ON SCREEN
declare
 f utl_file.file_type;
 s varchar2(2000);
begin
 dbms_output.enable(100000);
 f := utl_file.fopen(UPPER('b67M'),'B67M_EMP.TXT','r');
 loop
  utl_file.get_line(f,s);
  dbms_output.put_line(s);
 end loop;
exception
 when NO_DATA_FOUND then
  utl_file.fclose(f);
end;

No comments:

Post a Comment