Oracle实现Mysql里的G标志

2009年09月16日 作者: 大头刚 

这篇文章我曾经在chinaunix的blog发表过,现在转过来。
mysql中提供了一个G [g] 标志,放到sql语句后,可以使一行的每个列打印到单独的行。例如:

mysql> select * from test limit 2\G;
*************************** 1. row ***************************
     test1: 0
     test2: 0
     test3: 0
*************************** 2. row ***************************
     test1: 0
     test2: 0
     test3: 0
2 rows in set (0.02 sec)

oracle中没有类似的选项,不过,Tom Tkyte 大师开发了一个过程实现同样的功能:

CREATE OR REPLACE PROCEDURE print_table(p_query IN VARCHAR2) AUTHID CURRENT_USER IS
  l_theCursor   INTEGER DEFAULT DBMS_SQL.open_cursor;
  l_columnValue VARCHAR2(4000);
  l_status      INTEGER;
  l_descTbl     DBMS_SQL.desc_tab;
  l_colCnt      NUMBER;
  n             NUMBER;
BEGIN
  DBMS_SQL.parse(l_theCursor, p_query, DBMS_SQL.native);
  DBMS_SQL.describe_columns(l_theCursor, l_colCnt, l_descTbl);
  FOR i IN 1 .. l_colCnt LOOP
    DBMS_SQL.define_column(l_theCursor, i, l_columnValue, 4000);
  END LOOP;
  l_status := DBMS_SQL.EXECUTE(l_theCursor);
  n :=1;
  WHILE (DBMS_SQL.fetch_rows(l_theCursor) > 0) LOOP 
    DBMS_OUTPUT.put_line('******* '||n||' rows *******');
    FOR i IN 1 .. l_colCnt LOOP
      DBMS_SQL.column_value(l_theCursor, i, l_columnValue);
      DBMS_OUTPUT.put_line(RPAD(l_descTbl(i).col_name, 30) || ': ' || l_columnValue);
    END LOOP;
    DBMS_OUTPUT.put_line('------------------');
    n := n+1;
  END LOOP;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_SQL.close_cursor(l_theCursor);
    RAISE;
END;

这里小小修改了下大师的过程,加上了行数的显示。
建议将上述过程建在sys帐号下,并且在sys下建一个公共同义词,这样所有其他用户都可以用print_table了

SQLPLUS>create public synonym print_table for sys.print_table;
Synonym created.
 
exec print_table('select * from emp where rownum<3');
******* 1 rows *******
EMPNO         : 7369
ENAME         : SMITH
JOB         : CLERK
MGR         : 7902
HIREDATE        : 17-DEC-80
SAL         : 800
COMM         :
DEPTNO         : 20
------------------
******* 2 rows *******
EMPNO         : 7499
ENAME         : ALLEN
JOB         : SALESMAN
MGR         : 7698
HIREDATE        : 20-FEB-81
SAL         : 1600
COMM         : 300
DEPTNO         : 30
------------------
PL/SQL procedure successfully completed.

  • Comments (0)
  • Trackbacks (0)
Leave a comment Trackback

No comments yet.

No trackback yet.