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 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
Add a GUID ( uniqueidentifier
) column to your cache table. Have each executing instance of the stored procedure create a new GUID ( NEWID()
) to uniquely identify it's rows in the cached table. That way you do not need to lock out other running instances.
When done, delete the rows that match your GUID only.
isn't that CacheTable a temporary table, so each instance of the stored procedure should allocated it's own; thus avoiding the locking problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.