请教一个存储过程的写法。我初学ORACLE不久,不会写存储过程,但又急用。请大家帮忙。table1有中字段COL1,值唯一,table2中字段col2,其值是table1中的col1,但不唯一,
例如
table1中
col1
1
2
3
....
table2中
col2
1
1
1
2
3
......
现在想找出在table1中有一行而在tabl2中也只有一行的记录(如2,3),写到table3中去,请教怎么写这个存储过程?

解决方案 »

  1.   

    create or replace procedure test
    is 
      vnum number;
    begin
      for rec in (select * from table1) loop
        select count(*) into vnum from table2 where col2=rec.col1;
        if vnum=1 then 
         insert into table3(col3) values(rec.col1);
         commit;
        end if;
      end loop;
    end;
      

  2.   

    同意楼上的存储过程方法,你还可以直接用查询语句做insert into table3
    (col3)
    select t.col2
    from (select t.col2,
         count(*) rn
    from table2 t
    group by t.col2) t,
    table1 t1
    where t1.col1(+) = t.col2
    and t.rn = 1
      

  3.   

    INSERT INTO TABLE3
    SELECT T1.col1
    FROM   table1 T1
    INTERSECT
    SELECT J1.col2
    FROM   (SELECT T2.col2,COUNT(1)
              FROM   table2 T2
         GROUP  BY T2.col2
            HAVING COUNT(1) = 1) J1
      

  4.   

    建议采用楼上的做法,使用having字句在聚合后对组记录进行筛选