Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old September 1st, 2008, 03:19 PM
Newbie
 
Join Date: Sep 2008
Posts: 1
Default How to prevent duplicate insertion without locking the entire table?

Hello,
I've a scenario with multiple threads that performs select/insert/update on the same table.
Basically, the flow is:

Code:
SELECT * FROM tablex where pk=?
if empty
Code:
INSERT into tablex values(...)
else
Code:
UPDATE tablex set ... where pk=?
where ph is the primary key ot tablex
To improve performance, I'd like that threads with different Pks will run without blocking, but threads with the same PK will be "serialized".
Using SELECT FOR UPDATE WITH RS is fine when the row already exists, but produce duplicate insert when the row doesn't exist yet, and two thread are trying to insert it.
Using TRANSACTION_SERIALIZABLE or SELECT FOR UPDATE WITH RR cause a table lock, and so threads with different Pks are blocked.
Is there a basic pattern to solve this problem?

Environment: Db2 V9.1 on Windows. Using a normal Java application
Reply
  #2  
Old September 1st, 2008, 09:53 PM
docdiesel's Avatar
Moderator
 
Join Date: Aug 2007
Location: Munich
Posts: 279
Default

Hi,

did you try the MERGE statement (http://publib.boulder.ibm.com/infoce...c/r0010873.htm ) ? Something like the following could be working:
Code:
MERGE INTO mytable mta
USING
  (SELECT pk FROM mytable where pk=xxx) mtb
ON (mta.pk=mtb.pk)
WHEN MATCHED THEN
  UPDATE
  SET field = value
WHEN NOT MATCHED THEN
  INSERT
    (fields)
  VALUES
    (values)
Regards,

Bernd
Reply
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles