I’m running into a deadlock problem when trying to lock some records so that no process (Windows service) picks the items to service them, then update the status and then return a recordset.
Can you please let me know why am I getting the deadlock issue when this proc is invoked?
CREATE PROCEDURE [dbo].[sp_LoadEventsTemp]
(
@RequestKey varchar(20),
@RequestType varchar(20),
@Status varchar(20),
@ScheduledDate smalldatetime = null
)
AS
BEGIN
declare @LoadEvents table
(
id int
)
BEGIN TRANSACTION
if (@scheduledDate is null)
Begin
insert into @LoadEvents (id)
(
Select eventqueueid FROM eventqueue
WITH (HOLDLOCK, ROWLOCK)
WHERE requestkey = @RequestKey
and requesttype = @RequestType
and [status] = @Status
)
END
else
BEGIN
insert into @LoadEvents (id)
(
Select eventqueueid FROM eventqueue
WITH (HOLDLOCK, ROWLOCK)
WHERE requestkey = @RequestKey
and requesttype = @RequestType
and [status] = @Status
and (convert(smalldatetime,scheduleddate) <= @ScheduledDate)
)
END
update eventqueue set [status] = 'InProgress'
where eventqueueid in (select id from @LoadEvents)
IF @@Error 0
BEGIN
ROLLBACK TRANSACTION
END
ELSE
BEGIN
COMMIT TRANSACTION
select * from eventqueue
where eventqueueid in (select id from @LoadEvents)
END
END
Thanks in advance.
Deadlocks happen most often (in my experience) when differnt resources are locked within differnt transactions in different orders.
Imagine 2 processes using resource A and B, but locking them in different orders.
– Process 1 locks resource A, then resource B
– Process 2 locks resource B, then resource A
The following then becomes possible:
– Process 1 locks resource A
– Process 2 locks resource B
– Process 1 tries to lock resource B, then stops and waits as Process 2 has it
– Process 2 tries to lock resource A, then stops and waits as Process 1 has it
– Both proceses are waiting for each other, Deadlock
In your case we would need to see exactly where the SP falls over due to a deadlock (the update I’d guess?) and any other processes that reference that table. It could be an trigger or something, which then gets deadlocked on a different table, not the table you’re updating.
What I would do is use SQL Server 2005’s OUTPUT syntaxt to avoid having to use the transaction…