Search code examples
sqlfor-loopplsqlconditional-statementsforall

2 requirements: 1) Replace multiple FOR loop with FORALL 2) use IF-THEN-ELSE condition while inserting data into table


My requirement is a bit different. I have two nested FOR loops that fetch data and based on certain condition it inserts sorted data into table.

Original code below:

FOR Name_1 IN First_Cursor
LOOP
  FOR Name_2 IN Second_Cursor (Name_1.Table_Field_Name)
  LOOP
    IF (Condition)
      THEN
        Prevalidation of data

        INSERT INTO <Table_Name>
          VALUES (..............................);
      ELSE
        IF (Condition)
        THEN
          Prevalidation of data

          UPDATE <Table_Name>
            WHERE .....................;

      END IF;
    END IF;
  END LOOP;
END LOOP;

I have to convert this whole code into FORALL

I tried many code but dint succeed in any, I think the syntax itself is wrong

IF (Condition)
THEN
  Prevalidation of data

  FORALL Name_2 IN Second_Cursor (Name_1.Table_Field_Name) of Name_1
    INSERT INTO <Table_Name>
      VALUES (..............................);
ELSE
  IF (Condition)
  THEN
    Prevalidation of data
    FORALL Name_2 IN Second_Cursor (Name_1.Table_Field_Name) of Name_1
      UPDATE <Table_Name>
        WHERE .....................;    
  END IF;
END IF;

Solution

  • please use "case" statement in sql look like :

    syntax:

    CASE [ expression ]
    
       WHEN condition_1 THEN result_1
       WHEN condition_2 THEN result_2
       ...
       WHEN condition_n THEN result_n
    
       ELSE result
    
    END
    

    SQL:

     select column1,column2,
        ( case when col3>0 then col4 else col5 end) as 'col_name' ,
        ( case when col6='value' then col7 else col8 end) as 'col_name1' 
        from 
        table_name
        where col_name13>45