日期:2014-05-16  浏览次数:20512 次

写入到blob字段的存储过程
create or replace procedure write2blob(directions blob,
                                      v_blob     blob,
                                      v_pos      integer
                                      
                                      )is

  v_1time_maxlength integer; --一次读取的最大长度
  amount            integer; --总长度
  v_blob_sub        blob; --一次读取的长度
  v_index           integer; ---索引
  v_sub_count       integer;
  offset            integer;
  directions2       blob;
begin

  v_1time_maxlength := 32767; --允许的长度
  amount            := length(v_blob); --blob的总长度
  v_sub_count       := amount / v_1time_maxlength + 1; --分成子串的个数
  v_index           := 1; --索引从1开始
  offset            := v_pos;
  directions2       := directions;
  loop
    dbms_output.put_line(length(v_blob));  
  
    DBMS_LOB.read(v_blob, v_1time_maxlength, offset, v_blob_sub); --读至v_blob_sub中
    dbms_lob.writeappend(directions2, length(v_blob_sub), v_blob_sub); --将v_blob_sub中的内容写到字段中
    v_index := v_index + 1;
  
    offset := v_index * v_1time_maxlength + 1;
    exit when v_index > v_sub_count;
  
  end loop;

  dbms_lob.close(directions2);
exception
  when no_data_found then
    dbms_output.put_line('找不到数据');
end;

测试代码:

-- Created on 2013-3-8 by ZHANGXL 
declare 
  -- Local variables here
  i integer;
  v_blob blob;
  directions blob;
  v_post_id number(18):=8814;
begin
  select pt.post_text into v_blob from jforum_posts_text pt where pt.post_id=8817;
  -- Test statements here
  --execute updateblob(jforum_posts_text,post_id,post_text,8817,0,v_blob);
   --update jforum_posts_text pt
    --                       set pt.post_text = EMPTY_BLOB()
    --                     where pt.post_id = v_post_id;
  select pt.post_text into directions from jforum_posts_text pt where  pt.post_id=v_post_id for update; --锁住
  dbms_lob.open(directions, dbms_lob.lob_readwrite);--打开读写流
    write2blob(directions,v_blob,1);
  commit;
end;



表结构:

-- Create table
create table JFORUM_POSTS_TEXT
(
  POST_ID      NUMBER(18) not null,
  POST_TEXT    BLOB,
  POST_SUBJECT VARCHAR2(200),
  ISDELETED    NUMBER(1) default 0
)
tablespace XZFY
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 128
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints 
alter table JFORUM_POSTS_TEXT
  add primary key (POST_ID)
  using index 
  tablespace XZFY
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    minextents 1
    maxextents unlimited
  );