How to avoid deadlock when multithreading updates one table same time?
558902Nov 17 2007 — edited Nov 22 2007Multithreading calls the stored procedure at the same time to update data in one table. For a instance,
Table1
Col1 Col2 Col3
-------------------------------
C1 1 1
C1 2 2
C1 3 3
C2 1 1
Table2
Col1 Col2 Col3
-------------------------------
C1 1 10
C1 2 4
C1 3 3
C2 1 1
There are several steps I want:
1. Get the data in Table1 where Col1 = C1 in a cursor which has Col1 column and Col2 column.
2. Cycle them one by one, and get the Col3 data from Table2 where Col1 = C1 and Table2.Col2 = Table1.Col2. (Due to deadlock is my concern, we use temp table, definityly it is not a good way. :( )
3. Update Table1 Set Col3 = Table2.Col3.
My new idea is when I get the collection from Table1 which Col1 = C1, I use this way below.
First I set transaction in below way.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
Then
select * from Table1 where Col1 = C1 for update nowait;
In my opinion, if one thread lock the data for update, other thread won't select out that locked data. Does it work?
Thank you.
Best regards,
Andreas