Q

Skipping record that already exists with insert statement

I have to do an insert statement, and I want to do it with cursors. But if a record already exists in the destination table, I want to skip it and insert the next record. Can anyone help me do that?

Hi. I have to do an insert statement, and I want to do it with cursors. But if a record already exists in the destination table, I want to skip it and insert the next record. Can anyone help me do that?

You can use a "merge" SQL statement. I have an example below:

I have two tables: scott.emp and scott.bonus. Below is the "merge" SQL statement:

 MERGE INTO bonus b USING (SELECT ename, job, sal, comm FROM emp WHERE ename IN ('SMITH', 'JAMES', 'TURNER', 'MARTIN', 'MILLER')) s ON (b.ename = s.ename) WHEN MATCHED THEN UPDATE SET b.comm = 700 WHEN NOT MATCHED THEN INSERT (b.ename, b.job, b.sal, b.comm) VALUES (s.ename, s.job, s.sal, 150);

The above merge will update the bonus comm field to 700 if the ename in bonus matches the ename in emp. If not, a new bonus record is inserted from the emp table.

Since you do not want to update and you have to use the update clause, you can change that clause to say:

 update set b.comm = b.comm
This was first published in August 2006

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close