views:

18

answers:

2

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:

  1. Delete everything in the CacheTable
  2. Populate the cacheTable
  3. 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!)
  4. 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

+1  A: 

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.

Mitch Wheat
This is a great solution as long as the GUID field is indexed. I like it!
hamlin11
+1  A: 

isn't that CacheTable a temporary table, so each instance of the stored procedure should allocated it's own; thus avoiding the locking problem

Dan D
It isn't a temporary table. Based upon your answer, I guess you're suggesting that it should be. Each instance of a stored procedure gets its own copy of a temporary table? That solves my problem all on its own if it's the case
hamlin11
I verified that SP's get their own instance of equivalent named temp tables, so this solution is what I went with, though the level of detail in the answer is lacking.
hamlin11