Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 434
  • Last Modified:

Oracle SQL Questions for combined INSERT/UPDATE?

I have a table with 4 columns:

ID (Primary Key)
Name
Data1
Data2

I need a single SQL statement to perform an update if the primary key in the sql already exists or an insert if the primary key does not already exist? Any ideas? I'm hoping there is some way to do this in one statement.

I could easily do an SQL statement in my code to see if the primary key exist then do an if else to do either an insert/update, but that sounds like a waste of code and inneficient if an single oracle SQL query would cover both for me.
0
KGNickl
Asked:
KGNickl
2 Solutions
 
wdosanjosCommented:
0
 
HainKurtSr. System AnalystCommented:
not one statement but:

option 1:

begin
  insert ...
exception
when DUP_VAL_ON_INDEX then
  update ...
when others then null;
end;

option 2:

select count(1) into cnt from ...
if (cnt=0)
  insert
else
  update

option 3:

MERGE which is posted before...
0
 
ms_sanjayCommented:
or you can do like this
update tablename set name=<<ne name>> where id=id;

if sql%norfound then
   insert into table name values(id,name,data1,data2)

Hope this helps.

Thanks
Sippy
0
 
awking00Commented:
What is the source for your updates or inserts? Is it a file or another table?
0
 
Mark GeerlingsDatabase AdministratorCommented:
Without knowing anything about the percentage of inserts compared to updates, your most efficient option is likely to use the "merge" syntax that Oracle SQL supports now.  

Also, remember that using PL\SQL is almost always slower than using SQL by itself, so the PL\SQL examples using "if" statements and "exception" sections will likely be slower than a straight SQL solution.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now