oracle 使用游标

 

oracle  使用游标进行多个表联合查询

declare
    --定义游标
     cursor mycur is 
            select t.dept_id,m.station_id,m.name from person_inform t
            left join contacts m
            on t.dept_id=m.id
            order by t.dept_id;
            
     --临时字段
    dept_id person_inform.dept_id%type;  
    station_id contacts.station_id%type;
    name contacts.name%type;  
        
begin
     open mycur;
     loop
            fetch mycur into dept_id,station_id,name;
            exit when mycur%notfound;
            dbms_output.put_line(dept_id||'  '||station_id||'  '||name);
     end loop;     
     close mycur;
end;

单表查询

declare
    --游标
     cursor mycur2 is  select t.* from person_inform t;         
            
     --行变量
     onerow person_inform%rowtype; 
        
begin
     open mycur2;
     loop
            fetch mycur2 into onerow;
            exit when mycur2%notfound;
            dbms_output.put_line(onerow.id||'  '||onerow.name);
     end loop;     
     close mycur2;
end;

单表查询时,执行SQL语句.

 

declare
    --游标
     cursor mycur2 is  select t.* from person_inform t;         
            
     --行变量
     onerow person_inform%rowtype; 
        
begin
     open mycur2;
     
     loop
            fetch mycur2 into onerow;
            exit when mycur2%notfound;
            
             if   onerow.name='a'   then                    
                  update person_inform set name='aaa' where id=onerow.id;
                  dbms_output.put_line('执行成功__11');
                  
             elsif onerow.name='ssss'   then                    
                  update person_inform set name='s' where id=onerow.id;
                  dbms_output.put_line('执行成功__22');   
                             
             else
                   dbms_output.put_line(onerow.id||'  '||onerow.name);                   
             end if;
           
     end loop;     
     close mycur2;
end;

 

 执行语句

declare
    --定义游标
    cursor mycur is
        select m.station_id, m.name, t.dept_id, t.name, t.id
        from   person_inform t
        left   join contacts m
        on     t.dept_id = m.id
        order  by t.dept_id;

    --临时字段
    m_station_id contacts.station_id%type;
    m_name       contacts.name%type;
    t_dept_id    person_inform.dept_id%type;
    t_name       person_inform.name%type;
    t_id         person_inform.id%type;

begin
    open mycur;
    loop
        fetch mycur
            into m_station_id, m_name, t_dept_id, t_name, t_id;
        exit when mycur%notfound;
    
        if m_station_id > 0 then
            dbms_output.put_line('----' || m_station_id || '  ' || m_name || '  ' ||
                                 t_dept_id || '  ' || t_name || '   ' || t_id);
        
            update person_inform
            set    dept_id = m_station_id
            where  id = t_id;
        end if;
    
    end loop;
    close mycur;
end;


 

 

你可能感兴趣的:(JOIN,oracle,sql)