I am trying to create a SQL stored procedure which is scheduled to run every day which is responsible for inserting data into a SQL table Table B
from Table A
where there is a unique index column named Change_ID
in Table B
.
But there are some cases when the select query returns Change_IDs
from source table Table A
which are already present in the destination table Table B
in which case the insertion fails as the procedure throws Cannot insert duplicate key row in object 'dbo.TableB' with unique index
and job is aborted.
In the above case, I am trying to catch the exception and perform a delete on Table B to remove the duplicate and insert the row from Table A.
I have the following query and May I know a better way of handling this scenario.
BEGIN TRY
insert into TableB
( change_id
, item_id
, class
, subclass
, start_date
, end_date
)
select
change_id
, item_id
, class
, subclass
, start_date
, end_date
from openquery(ORA,'select * from TableA where start_date >= next_day(trunc(sysdate)-5,''MONDAY'')')
END TRY
BEGIN CATCH
--
END CATCH