1

Version: 17.3.1

I run some queries on daily basis.I want to add a code at the end of them so that it automatically exports tables to specific location on my computer, in specified format. Lets say to my desktop as xlsx.

Thank you.

1 Answer 1

1

1. Create directory to put data from table:

CREATE OR REPLACE DIRECTORY EXPORT_DATA AS 'c:\temp'

2. Create procedure:

CREATE OR REPLACE PROCEDURE export_to_csv
IS
   v_file     UTL_FILE.file_type;
   v_string   VARCHAR2 (4000);

   CURSOR c_emp
   IS
      SELECT empno,
             ename,
             deptno,
             sal,
             comm
        FROM emp;
BEGIN
   v_file :=
      UTL_FILE.fopen ('EXPORT_DATA',
                      'empdata.csv',
                      'w',
                      1000);

   -- if you do not want heading then remove below two lines
   v_string := 'Emp Code, Emp Name, Dept, Salary, Commission';
   UTL_FILE.put_line (v_file, v_string);

   FOR cur IN c_emp
   LOOP
      v_string :=
            cur.empno
         || ','
         || cur.ename
         || ','
         || cur.deptno
         || ','
         || cur.sal
         || ','
         || cur.comm;

      UTL_FILE.put_line (v_file, v_string);

   END LOOP;
   UTL_FILE.fclose (v_file);

EXCEPTION
   WHEN OTHERS
   THEN
      IF UTL_FILE.is_open (v_file)
      THEN
         UTL_FILE.fclose (v_file);
      END IF;
END;

3. Run procedure:

BEGIN
     export_to_csv;
END;
Sign up to request clarification or add additional context in comments.

2 Comments

Why you need this solution in SQL? In my opinion in SQL it's not possible.
I am gonna consecutively run my daily queries and I want SQL to export them to a specific location every day, then I will use those excels as source file for many reports using PowerQuery. I would like to directly import it to excel from SQL by connecting the database. but PowerQuery to SQL is locked/ not allowed by system/administer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.