Question

I would like to get a suggestion on improving my setup that is causing the sql server to return the deadlock message. I have multiple threading application that actually uses the TaskParallel library and each task will use a stored procedure to select an id from a table to use in its processing. I immediately delete that id from the table in the same statement and I think that is what is causing the deadlocks. The table consists of one column of uniques ids with no indexes. I thought of doing a batch delete periodically but that means keeping a tally of used ids across multiple servers.

here is my sql stored procedure:

   CREATE PROCEDURE [dbo].[get_Ids]
   @id nvarchar(20) OUTPUT

    AS

    BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
   SET NOCOUNT ON;

       Select top 1 @id = siteid from siteids 
       delete siteids where siteid = @id



   END

Is there any better way to do this? My processes work very fast and I used to request this id from a webrequest service but this took 3 seconds.

Was it helpful?

Solution

Some things to try: Maybe try hinting to the DB that you will delete the record you just selected, this way it will grab the lock early. For this to work you'll need to wrap the whole procedure in a transaction, then hint the select. Should look something like:

BEGIN TRANSACTION  
  SELECT TOP 1 @id = siteid from siteids WITH (UPDLOCK, HOLDLOCK)
  DELETE siteids WHERE siteid = @id
COMMIT TRANSACTION

Also make sure the siteid column is indexed(or tag it as primary key, since you say it is unique), otherwise it would have to scan the table to get the record to delete, which could make deadlocking worse since it spends a bunch more time deleting.

For deadlocks in general, run the SQL profiler and see what the deadlock graph looks like - might be something else is going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top