Need to use PLSQL to insert distinct rows

oracle-11g-r2plsql

I need to take some data from Table A, use some logic, and then insert one or more rows into Table B. I have a PLSQL block that brings in data from Table A with a cursor, performs all the logic required, and inserts the required rows.

The problem is there are duplicate rows in Table B – it's the nature of the beast. But I need the final result to be a Table B with no duplicates.

It's Oracle so temporary tables are bad form – what's the best way to accomplish this?

Best Answer

If the duplicates are being introduced by the inserts from Table A, then it seems a MERGE would be in order. A MERGE can INSERT data when the record does not exist in Table B and UPDATE data if the record already exists thus preventing the introduction of duplicates.

FrustratedWithFormsDesign is correct that you probably should have a constraint preventing the introduction of duplicates. He is also correct in pointing out that this code would probably benefit from Bulk processing.

Phil is correct that if you only need to INSERT data, then a subquery pruning rows from the insert would be preferable.