'How do I give an alias name to the values printed by dbms output in PL/SQL?

I have this following code which prints the department number and department name from dept table whose department number is less than 40.

declare
cursor cn is select dno, dname from dept where dno<40;
v_dno dept.dno%type;
v_dname dept.dname%TYPE;
begin
    open cn;
        loop
            fetch cn into v_dno,v_dname;
            dbms_output.put_line(v_dno||' '||v_dname);
            exit when cn%notfound;
        end loop;
    close cn;
end;

This is the output I got:

10 Administration
20 Marketing
30 Purchasing
30 Purchasing

But the output that I'm expecting is:

Department_No   Department_Name
10              Administration
20              Marketing
30              Purchasing
30              Purchasing


Solution 1:[1]

You'll have to display it separately (see line #10) (I used Scott's sample DEPT table as I don't have yours):

SQL> DECLARE
  2     CURSOR cn IS
  3        SELECT deptno, dname
  4          FROM dept
  5         WHERE deptno < 40;
  6
  7     v_deptno  dept.deptno%TYPE;
  8     v_dname   dept.dname%TYPE;
  9  BEGIN
 10     DBMS_OUTPUT.put_line ('Department_no   Department_name');
 11
 12     OPEN cn;
 13
 14     LOOP
 15        FETCH cn INTO v_deptno, v_dname;
 16
 17        DBMS_OUTPUT.put_line (RPAD (v_deptno, 15, ' ') || ' ' || v_dname);
 18        EXIT WHEN cn%NOTFOUND;
 19     END LOOP;
 20
 21     CLOSE cn;
 22  END;
 23  /
Department_no   Department_name
10              ACCOUNTING
20              RESEARCH
30              SALES
30              SALES

PL/SQL procedure successfully completed.

SQL>

Solution 2:[2]

You can write combination of plsql & html code. As like

declare
cursor cn is select dno, dname from dept where dno<40;
begin
htp.p('<table>
    <tr>
        <th>Department_no<\th>
        <th>Department_name<\th>
    <\tr>');
for i in cn
    loop
htp.p('<tr>
        <td>'|| i.dno ||'<\td>
        <td>'|| i.dname ||'<\td>
    <\tr>');
    end loop;
htp.p('<\table>');
end;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Littlefoot
Solution 2 Imran