Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dears,

My SQL Server procedure selecting and updating data and many source trigering same procedure and sometime same row updating from several sources, does it have any way how to reserve data for updating only from one source?

What I have tried:

select update but its not helped
Posted
Updated 31-Aug-20 5:59am

1 solution

One way is to use SELECT FOR UPDATE structure to lock the records during the select and release the locks upon COMMIT or ROLLBACK. For more information, see MySQL :: MySQL 8.0 Reference Manual :: 15.7.2.4 Locking Reads[^]

If you need to extend the control outside the boundaries of a transaction you can use TIMESTAMP data type to implement optimistic concurrency control. About TIMESTAMP see MySQL :: MySQL 8.0 Reference Manual :: 11.2.2 The DATE, DATETIME, and TIMESTAMP Types[^]

For an example of optimistic concurrency you can refer to How to Prevent When a Transaction Accidentally Overwrites Modified Data[^]. Even though the article is written for SQL Server, the principle is the same.

EDIT
Looking at the question again I felt unsure if you're using MySQL or SQL Server. If you're using Microsoft SQL Server, you can lock the records you select for example using WITH UPDLOCK hint in your query to ensure that the records are locked regardless of the concurrency settings. See Table Hints (Transact-SQL) - SQL Server | Microsoft Docs[^]

And in case of SQL Server the article should be accurate.
 
Share this answer
 
v2
Comments
[no name] 31-Aug-20 12:05pm    
That is a very interesting solution. Have a 5.
Wendelius 31-Aug-20 12:20pm    
Thank you :)
ZurdoDev 31-Aug-20 15:43pm    
However, if there are a lot of sources as OP mentions then you may create waits doing this. Although, SQL already locks a record when updating it so I'm not sure this does anything, does it?

I don't really feel like the OP explained themselves well. I feel like something else is really going on.
Wendelius 31-Aug-20 22:43pm    
Locking is basically waiting in queue so I would prefer using the existing mechanism over creating a custom one.

The difference in locking the data during select is in the type of the locks. When the select is run and update lock is required, no-one else can update that specific record until you release the lock. With the default behaviour, even if you have selected the data someone else can start updating it and ask for X lock since only S lock is acquired during select.

It's quite possible that OP has left something relevant out. If that's the case, let's hope they give more info :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900