ROWNUM仅适用于一行。之后如何获取行?

时间:2018-07-02 12:32:16

标签: oracle plsql blob rownum

我想提取BLOB数据并从中写入文件(建议它应该是excel或txt或任何其他文件)。一个单元格最多可包含60k个字符。我想编写一个脚本,用BLOB数据读取整个表并将其写入文件。在下面的代码中,ROWNUM仅适用于一行。有什么选择?还是有另一个脚本可以帮助我实现读取BLOB和写入文件的最终目标?

SET SERVEROUTPUT ON;
    DECLARE
       TotalRows NUMBER;
       TotalChar NUMBER;
       CharCounter NUMBER;
    BEGIN
    SELECT count(*) INTO TotalRows FROM <TableName>;
            --dbms_output.Put_line(RC);
            --END;
       FOR RC IN 1..TotalRows
       LOOP
           -----------------Code for Rows starts--------------------------------------------------------------------------------
            dbms_output.Put_line('Row '||RC||' Started.');
            SELECT Length(<ColumnWithBLOBDataType>) INTO TotalChar FROM <TableName> where **Rownum = RC**;
            dbms_output.Put_line('Crossed Char counting query. TotalChar='||TotalChar);
            CharCounter:=TotalChar/2000+1;
            dbms_output.Put_line('Loop will run these many times= '||CharCounter|| ' and Total Chars=' ||TotalChar);
            For CC IN 1..CharCounter
            LOOP
                dbms_output.Put_line('Trip: '||CC);
            END LOOP;  
        -----------------Code for Rows Ends----------------------------------------------------------------------------------------
            TotalChar :=0;
            dbms_output.Put_line('Row '|| RC||' Done. TotalChar='|| TotalChar);
       END LOOP;
       dbms_output.Put_line('Exited loop 1.');
    END;

1 个答案:

答案 0 :(得分:1)

您通常不使用ROWNUM从表中选择行。这是不安全的,没有必要。通常,您可以使用单个FOR SELECT循环来完成此操作:

DECLARE
   CharCounter NUMBER;
   part VARCHAR2(30000);
   offset NUMBER;
BEGIN
  FOR r IN (SELECT c,
                   rownum as rc,
                   dbms_lob.getlength(c) as totalchar
              FROM mytable)
  LOOP
    -----------------Code for Rows starts--------------------------------------------------------------------------------
    dbms_output.put_line('Row '||r.rc||' Started.');

    dbms_output.put_line('Crossed Char counting query. TotalChar='||r.totalchar);

    offset := 1;
    WHILE (offset <= r.totalchar) LOOP
      part := dbms_lob.substr(r.c, 20000, offset);
      offset := offset + length(part);      
      dbms_output.put(part);
    END LOOP;
    dbms_output.put_line('');

  END LOOP;
END;
/