I am populating a table that acts as a cache. (This is needed because the data comes through a linked server and joins through the link are too expensive)
I've included pseudo code below that hopefully demonstrates what I'm trying to do. I really don't know if there's a way to lock a table down like this, or if I need to use transactions, but here's the basics:
- Delete everything in the CacheTable
- Populate the cacheTable
- Process the data in CacheTable for 10 seconds (it's important that other instances of this stored procedure don't delete the CacheTable during processing!)
- Return the processed results (CacheTable is free again)
delete from CacheTable -- If this errors because it is locked, exit stored procedure
[[Lock CacheTable]]
insert into CacheTable
exec RemoteDB.dbo.[sp_GrabRecords] @Start, @End, @Key
Process Cached Data
...
Select Processed Data
[[Unlock CacheTable]]
How can I protect the data in this CacheTable while it is being processed?
Note: I'm also looking for alternatives. I tried using a table variable, but it was too slow, probably because it didn't have a primary key. Not even sure if tables variables can have primary keys. I just know the method above is extremely fast, but it has a problem with collisions, obviously