DEV Community

Zoboki Árpád
Zoboki Árpád

Posted on

1

Loop on static content to upsert many rows in Oracle SQL

Sometimes you just want to add many test rows into your Oracle DB, by iterating over fixed content. If your DB already has some rows which you then need to update, then what you're looking for is the upsert (update or insert) operation.

Here's one example how to do this in Oracle SQL, without creating a temporary table:

begin
for i in (select * from table(sys.dbms_debug_vc2coll('1234','5678')))
loop
merge into my_target_table target
using (
  select i.COLUMN_VALUE as acc_no,
  'N' as static_val,
  '1' as another_static_field
  from dual
  ) temp on (target.acc_no = temp.acc_no)
when matched then
  update set target.MY_FIELD_TO_UPDATE = temp.static_val, target.SECOND_FIELD = temp.another_static_field
when not matched then
  insert values (temp.acc_no, temp.static_val, temp.another_static_field);
end loop;
end;
/
Enter fullscreen mode Exit fullscreen mode

All parts of this syntax are necessary, including the ending / which signifies the end of the anonymous PL/SQL code block, so you can execute it in e.g. SQuirrel SQL.
sys.dbms_debug_vc2coll('1234','5678') this call outputs whatever list of data you need to loop over
from dual using the special dual table keyword, we don't have to create a table to hold our static data, it will be in memory only
when matched then the matched directive allows us to do the upsert operation (update when already existing, insert when new)
i.COLUMN_VALUE pay special attention to the .COLUMN_VALUE field, which is how Oracle allows us to access each single value that is being looped over

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay