Home » SQL & PL/SQL » SQL & PL/SQL » Conditional INSERT (11g)
Conditional INSERT [message #627304] Mon, 10 November 2014 14:51 Go to next message
shree_z
Messages: 75
Registered: February 2008
Member
In table t1, how can I insert only those rows that doesnt exist already. If a row exists, I want to skip inserting that row.

for rec in (select column1, column2....columnn,
	    from table1,table 2, table3, table4
	    where conditions)

     loop

      begin

        insert into t1
        values  (rec.column1, rec.column2 ..)

      end;

    end loop;


Thanks in advance.

[Updated on: Mon, 10 November 2014 14:52]

Report message to a moderator

Re: Conditional INSERT [message #627306 is a reply to message #627304] Mon, 10 November 2014 14:53 Go to previous messageGo to next message
cookiemonster
Messages: 13919
Registered: September 2008
Location: Rainy Manchester
Senior Member
Write a single insert/select statement. Have the where clause exclude rows already in t1.
Re: Conditional INSERT [message #627307 is a reply to message #627304] Mon, 10 November 2014 14:56 Go to previous messageGo to next message
BlackSwan
Messages: 26766
Registered: January 2009
Location: SoCal
Senior Member
https://docs.oracle.com/database/121/SQLRF/statements_9016.htm#SQLRF01606
Re: Conditional INSERT [message #627400 is a reply to message #627307] Tue, 11 November 2014 10:55 Go to previous messageGo to next message
shree_z
Messages: 75
Registered: February 2008
Member
Thanks for the replies. I ended up adding the condition in the cursor itself.
Re: Conditional INSERT [message #627417 is a reply to message #627400] Tue, 11 November 2014 14:07 Go to previous message
Bill B
Messages: 1971
Registered: December 2004
Senior Member
You never needed a cursor. simply do

insert into t1
select column1, column2....columnn,
from table1,table 2, table3, table4
where conditions
and not exists
(select null
from t1 a
where a.key_column_for_t1 = table1.col1
and conditions);

[Updated on: Tue, 11 November 2014 14:08]

Report message to a moderator

Previous Topic: date validation
Next Topic: ORA-01031: insufficient privileges
Goto Forum:
  


Current Time: Tue Apr 16 03:19:38 CDT 2024