I have an issue that the same stored procedure is being invoked at exactly the same time with exactly the same paramenters.
The purpose of the stored procedure is to fet
Trouble is in doing a select and then insert then normally there is a read lock for the select and then a write lock on the insert. Without a transaction then the timing of many updates will often allow multiple inserts to happen as you see. In a transaction the first read lock will stop other processes getting a write lock and if more than one process gets a read lock then none can get a write lock and so you get a deadlock.
In this case I would alter the insert code so that the indices only allow one insert to work ie you have a unique key and only one process will ne able to insert the data so getting no duplicates. The process for updating is then in a transaction either
1) do the insert first and deal with an exception or error if it tries inserting a duplicate
or 2) do a HOLD LOCK (Sybase and SQL Server)on doing the select first - thus the first to lock gets the full permission to insert if needed
or 3) Possibly use the merge command if the RDBMS allows it. This does the check and insert all in one command but will always change the database.
EDIT: I think there is no real alternative to 1 if you need to make sure there is one and only one record inserted as the test for that has to be in a transaction.
the cost could be cut by checking for existence forst in one transaction and then secondly doing the insert and check in another transaction. Thus in most cases you just have a select and in the other cases you get the full slow insert and check but this should occur less often.