1

I am able to get the result as CSV in Oracle by using this simple query with a hint.

SELECT /*csv*/ * FROM dual;

This returns

"DUMMY"
"X"

Now I would like to use exactly the same hint in PL/SQL in order not to reinvent the wheel.

SET SERVEROUTPUT ON;
declare
  cur sys_refcursor;
  csv_line varchar2(4000);
begin
  open cur for select /*csv*/ * from dual;
  loop
    fetch cur into csv_line;
    exit when cur%NOTFOUND;
    dbms_output.put_line(csv_line);
  end loop;
  close cur;
end;

Unfortunately this prints only

X

which seems to ignore the hint.

Any way to do it that simple or do I have to write a special piece of code for exporting the data as CSV?

1 Answer 1

5

The /*csv*/ hint is specific to SQL Developer and it's sibling SQLCl; and is somewhat superseded by the set sqlformat csv option.

It is not a hint recognised by the optimiser; those are denoted by a plus sign, e.g. /*+ full(...) */ or less commonly --+ full(...).

If you're creating the output in PL/SQL you will need to construct the string yourself, adding the double quotes and delimiters. You can either have the cursor query do that so you can select into a single string even when you have multiple columns; or have a 'normal' query that selects into a record and have PL/SQL add the extra characters around each field as it's output.

It would be more normal to use utl_file than dbms_output as the client may not have that enabled anyway, but of course that writes to a directory on the server. If you're writing to a file on the client then PL/SQL may not be appropriate or necessary.

If you need to do some manipulation of the data in PL/SQL then one other option is to use a collection type and have an output/bind ref cursor, and then have SQL Developer print that as CSV. But you don't normally want to be too tied to a single client.

Sign up to request clarification or add additional context in comments.

1 Comment

Pity. Thanks for the answer though! I think I will go with UTL_FILE.

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.