SQL - How can I temporarily protect the data in this table?
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 D开发者_运维问答ata
[[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
isn't that CacheTable a temporary table, so each instance of the stored procedure should allocated it's own; thus avoiding the locking problem
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.
精彩评论