Search code examples
sqloracle-databaseplsql

How to use a value in a column as repetition count


I have an update statement that needs to be run as many times as a value in another table. Here are what the tables look like

TABLE 1

ROW_ID CLOB_TEXT
1 text
2 text

TABLE 2

HOW_MANY_TIMES ROW_ID
1 1
4 2

Basically update statement should run on the first row, but how many times that it will runn will be dependent based on the first col from the second table. And i have ROW_ID col on the both tables to link them to prevent repetitions.

Should i convert my second table to the format below and run updates for each row? Or is there another way to do it maybe?

COL1 ROW_ID
1 1
1 2
2 2
3 2
4 2

I can do single updates for each row but i can't seem to do it in a loop(?) based on a counter from another table it seems.


Solution

  • Is this what you're talking about?

    begin
      for cur_2 in (select row_id, how_many_times from table2) loop
        for i in 1 ..cur_2.how_many_times loop
          update table1 set
            clob_text = replace(clob_text, 'A', 'B')
            where row_id = cur_2.row_id;
        end loop;
      end loop;
    end;
    /