1. select threadid, subject  from thread
得到很多数据如何写一个function把threadid, subject插入 keyword表中, 
insert into keyword values(keyword_id,threadid, subject), 
keyword_id是原来表中最大的keyword_id值, 之后插入keyword_id要加一
得到keyword_id,
并接着插入keyword表
insert into theadkeyword values(thread_id, keyword_id )
请帮忙写一个function实现这个功能

解决方案 »

  1.   

    create or replace procedure pro 
    is
       v_keyword_id number := 0;
    begin
       select nvl(max(keyword_id),0) into v_keyword_id from keyword;
       for i in (select threadid, subject from thread) loop
          v_keyword_id := v_keyword_id + 1;
          insert into keyword values(v_keyword_id,i.threadid, i.subject);
          insert into theadkeyword values(i.threadid, v_keyword_id );
       end loop;
    end pro;这个方案虽然给你实现了,但是系统资源消耗不小,为什么不建一个sequence和一个trigger解决呢
      

  2.   

    create or replace function DemoFun( threadid number,subject number ) return number 
    is
       a_keywordid number := 0;
    begin
     begin
       select nvl(max(keyword_id),0) + 1 into a_keywordid from keyword;
       insert into keyword values(a_keywordid,threadid, subject);
       insert into theadkeyword values(threadid, a_keywordid );
     exception
       when others then
       return 0;
     end;
       return a_keywordid;
    end DemoFun;
      

  3.   

    thanks, 如果i.subject在keyword 表中存在了,就不进行插入, 怎么写这个代码呢?
    insert into keyword values(v_keyword_id,i.threadid, i.subject);
      

  4.   

    改下for里面的sql不就可以了吗,在keyword中存在的记录就不查出来   for i in (select threadid, subject 
                 from thread t1
                 where not exists (select rowid 
                                   from  keyword t2
                                   where t2.subject = t1.subject)) loop
      

  5.   

    函数不能实现你的需求,function里面不能有insert等DML语句可以用序列实现你的需求
      

  6.   

    如果keyword_id是主键或唯一值的话,这种从原表中取最大值加1方式
    在并发状态下可能存在问题,多个用户取到同一keyword_id会只有一个插入语句成功,
    其它都会失败,如果没有主键或唯一约束的话,表中keyword_id会重复。如果是主键,最好用序列,并发没问题
      

  7.   

    insert into key_word 
    (select (select nvl(max(keyword_id),0) from key_word)+rownum,
    ,threadid, subject from thread)