如何在使用PL SQL执行时在屏幕上显示sql语句结果?

时间:2014-08-29 12:22:27

标签: sql plsql screen

早上好,

我想使用PL SQL代码执行查询,我希望将结果显示给用户,就像他自己执行SQL一样。总之,我希望结果像往常一样显示在屏幕上。它是在另一个主题中报告的相同问题:

How to output result of SELECT statement which is executed using native dynamic SQL?

我尝试应用下面链接中建议的解决方案,但它没有用。这里我的代码无法正常工作:

DECLARE

    cursor_ID  NUMBER;
    tbl_name VARCHAR2(256);
    record_count INTEGER;
    numRows  INTEGER;

    sql_instruction VARCHAR(10000);
    interface_table_name VARCHAR2(50);
    interfaces_record ALL_TABLES%rowtype;
    CURSOR interfaces_cursor IS 
      SELECT table_name, ROW_NUMBER()OVER(ORDER BY 1) record_number,
               COUNT(*)OVER() total_records FROM ALL_TABLES where table_name like '%TBL_%';

    BEGIN

      FOR interfaces_record in interfaces_cursor
      LOOP
        interface_table_name := interfaces_record.table_name;
        IF interfaces_record.record_number = 1 THEN
          sql_instruction := sql_instruction || ' SELECT ''' || interface_table_name || ''' AS TABELA, COUNT(*) AS QTDE_REGISTROS FROM ' || interface_table_name;
        ELSE
          sql_instruction := sql_instruction || ' UNION ALL SELECT ''' || interface_table_name || ''' AS TABELA, COUNT(*) AS QTDE_REGISTROS FROM ' || interface_table_name;
        END IF;
      END LOOP;
      dbms_output.put_line('SQL: ' || sql_instruction);
      --EXECUTE IMMEDIATE sql_instruction; --this don't show the result on the screen

      -- THIS PART BELLOW IS WHAT I DID TO TRY SHOW THE RESULT ON THE SCREEN
      cursor_ID := DBMS_SQL.OPEN_CURSOR;

      DBMS_SQL.PARSE(cursor_ID, sql_instruction, DBMS_SQL.native);
      DBMS_SQL.DEFINE_COLUMN(cursor_ID, 1, tbl_name, 256);
      DBMS_SQL.DEFINE_COLUMN(cursor_ID, 2, record_count);

      numRows := DBMS_SQL.EXECUTE(cursor_ID);
      LOOP
            IF DBMS_SQL.FETCH_ROWS(cursor_ID) = 0 THEN
                 EXIT;
            END IF;

            DBMS_SQL.COLUMN_VALUE(cursor_ID, 1, tbl_name);
            DBMS_SQL.COLUMN_VALUE(cursor_ID, 2, record_count);

            --DBMS_OUTPUT.PUT_LINE(tbl_name || ' ' || record_count);
      END LOOP;

      EXCEPTION
            WHEN OTHERS THEN
                      RAISE;
            DBMS_SQL.CLOSE_CURSOR(cursor_ID);
    END;

你知道为什么我的代码没有在屏幕上显示结果吗?我将不胜感激任何帮助。感谢。

2 个答案:

答案 0 :(得分:0)

使用DBMS_OUTPUT.PUT_LINE以便在屏幕上获得结果:)或者在脚本结尾处使用/它...如果您的脚本有任何错误,那么有时它也不会显示结果或显示任何错误在这种情况下,最好使用Exeption ..

答案 1 :(得分:0)

如果在SQL * Plus中执行PL / SQL代码,则需要SET SERVEROUTPUT ON并取消注释/包含DBMS_OUTPUT.PUT_LINE语句。

您可以在单个SQL语句中获得相同的结果

SELECT table_name
      ,to_number
         (extractvalue
            (xmltype
               (dbms_xmlgen.getxml
                  ('SELECT count(*) c FROM ' || owner || '.' || table_name)
               )
            ,'/ROWSET/ROW/C'
            )
         ) Count
  FROM all_tables
 WHERE table_name LIKE '%TBL_%'