Monday, March 22, 2010

Print Table Procedure

My first try about DBMS_SQL package. some thing i learnt newly today.

create or replace
procedure print_table(p_query in varchar2)
authid current_user
as
    l_cursor number := dbms_sql.open_cursor;
    l_sql varchar2(100) := p_query;
    l_column_count  number := 0;
    l_desctab   dbms_sql.desc_tab;
    l_column_value varchar2(4000);
    l_status number;
begin
    dbms_sql.parse(l_cursor,l_sql,dbms_sql.native);
    dbms_sql.describe_columns (l_cursor,l_column_count,l_desctab);

    for i in 1..l_column_count
    loop
        dbms_sql.define_column (l_cursor,i,l_column_value,4000);
    end loop;

    l_status := dbms_sql.execute(l_cursor);

    while ( dbms_sql.fetch_rows(l_cursor) > 0 )
    loop
        for i in 1..l_column_count
        loop
            dbms_sql.column_value (l_cursor,i,l_column_value);
            dbms_output.put_line ( rpad(' ',5,' ')||rpad(l_desctab(i).col_name,20,'-') ||' '|| l_column_value );
        end loop;
        dbms_output.put_line (' ');
    end loop;

    dbms_sql.close_cursor(l_cursor);
end print_table;


scott@10G> exec print_table (' select * from emp where rownum <= 2 ');
     EMPNO--------------- 7782
     ENAME--------------- CLARK
     JOB----------------- MANAGER
     MGR----------------- 7839
     HIREDATE------------ 09-JUN-81
     SAL----------------- 2450
     COMM----------------
     DEPTNO-------------- 10

     EMPNO--------------- 7839
     ENAME--------------- KING
     JOB----------------- PRESIDENT
     MGR-----------------
     HIREDATE------------ 17-NOV-81
     SAL----------------- 5000
     COMM---------------- 0
     DEPTNO-------------- 10

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.04

No comments:

Post a Comment