I have two tables, one "Import" and the other "Current". Every hour data is imported into Import, and I have a procedure that has to make sure to update Current with the new data from Import, for a specified date interval.
And if rows are missing from Import during that date interval it means they have been deleted, so they should also be deleted from Current. Here's where this query comes in:
delete from Current where CurrentId in
(
select CurrentId as id from (
select CurrentId from Current dd
where not exists
(
select d.* from Current d, Import tc
where d.date between @startdate and @enddate
and d.employeenumber = tc.employeenumber
and d.date = tc.date
and d.origin = tc.origin
and d.planid = tc.planid
and d.CurrentId = dd.CurrentId
)
and dd.date between @startdate and @enddate
) as x
);
So essentially in the inner loop it selects rows that are the same in both tables. Then it makes a select from Curret "where not exists" those rows to find the ones that needs deletion. It then gets the ID's and deletes them.
But with the amount of data I have it takes an hour and that's just too long... How can I speed this up?