Oracle: export a table with blobs to an .sql file that can be imported again

前端 未结 5 521
终归单人心
终归单人心 2020-12-16 00:40

I have a table \"Images\" with two fields:

  • Name VARCHAR2
  • Data BLOB

I would like to export that table to a .sql file which I could impor

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 01:29

    If you absolutely need to use a single .sql file to import the BLOB you can generate the script using PL/SQL:

    set serveroutput on
    declare
      lob_in blob;
      i integer := 0;
      lob_size integer;
      buffer_size integer := 1000;
      buffer raw(32767);
    begin
      select
        data, dbms_lob.getlength(data)
        into lob_in, lob_size
      from images
      where name = 'example.png';
    
      for i in 0 .. (lob_size / buffer_size) loop
        buffer := dbms_lob.substr(lob_in, buffer_size, i * buffer_size + 1);
        dbms_output.put('dbms_lob.append(lob_out, hextoraw(''');
        dbms_output.put(rawtohex(buffer));
        dbms_output.put_line('''));');
      end loop;
    end;
    

    Its output will be the BLOB's content encoded like:

    dbms_lob.append(lob_out, hextoraw('FFD8FFE0...0000'));
    dbms_lob.append(lob_out, hextoraw('00000000...0000'));
    ...
    dbms_lob.append(lob_out, hextoraw('007FFFD9'));
    

    Which you can load into an already inserted row with PL/SQL:

    declare
      lob_out blob;
    begin
      select data into lob_out
      from images
      where name = 'example.png'
      for update;
    
      dbms_lob.append(lob_out, hextoraw('FFD8FFE0...0000'));
      dbms_lob.append(lob_out, hextoraw('00000000...0000'));
      ...
      dbms_lob.append(lob_out, hextoraw('007FFFD9'));
    end;
    

    Just remember the resulting .sql file will be huge.

提交回复
热议问题