Search code examples
oracle-databaseif-statementstored-procedurescursor

LOOP into cursor until each IF ELSE true in oracle


I have written a cursor where I want to LOOP each and every column until it becomes true. So if all the IF statement matches to true then I want to insert the data into VALID table or at last I want to insert the incorrect data into the INVALID TABLE.

Below is the cursor. Kindly let me know whether my step is accurate or Do I need to make any changes in that.

create or replace procedure fiber_transm_valid_data as 
begin
  for cur_r in (select rj_span_id, 
                       rj_maintenance_zone_name,
                       rj_maintenance_zone_code                
                from app_fttx.transmedia@sat               
               )
  loop               
    if cur_r.rj_span_id > '0' then       
		elsif cur_r.rj_maintenance_zone_name = 'aa' then
			elsif  cur_r.rj_maintenance_zone_code = 'A123' then
				INSERT INTO VALID TABLE 
				(span_id, maintenance_zone_name,rj_maintenance_zone_code)
       values (cur_r.rj_span_id, cur_r.rj_maintenance_zone_name, cur_r.rj_maintenance_zone_code);
	   
	   ELSE
			INSERT INTO INVALID TABLE 
				(span_id, maintenance_zone_name,rj_maintenance_zone_code)
       values (cur_r.rj_span_id, cur_r.rj_maintenance_zone_name, cur_r.rj_maintenance_zone_code);
  end loop;  
end fiber_transm_valid_data;


Solution

  • Not quite like that; IF is wrong. Have a look at this.

    create or replace procedure fiber_transm_valid_data as 
      l_state_name table_of_states.rj_state_name%type;
    begin
      for cur_r in (select rj_span_id, 
                           rj_maintenance_zone_name,
                           rj_maintenance_zone_code,
                           rj_state_name
                    from app_fttx.transmedia@sat               
                   )
      loop         
        select max(rj_state_name) 
          into l_state_name
          from table_of_states
          where rj_state_name = cur_r.rj_state_name
            and rownum = 1;
    
        if     cur_r.rj_span_id > '0' 
           and cur_r.rj_maintenance_zone_name = 'aa' 
           and cur_r.rj_maintenance_zone_code = 'A123'
           and l_state_name = 1       
        then       
           INSERT INTO VALID_TABLE 
             (span_id, maintenance_zone_name,rj_maintenance_zone_code)
              values 
             (cur_r.rj_span_id, cur_r.rj_maintenance_zone_name, cur_r.rj_maintenance_zone_code);
        else
            INSERT INTO INVALID_TABLE 
              (span_id, maintenance_zone_name,rj_maintenance_zone_code)
               values 
              (cur_r.rj_span_id, cur_r.rj_maintenance_zone_name, cur_r.rj_maintenance_zone_code);
        end if;       
      end loop;  
    end fiber_transm_valid_data;