开发者

Locking several SQL Server records

My scenario is this. I have a single entity composed of several rows in several tables. Conceptually this can be seen as a single document. When a user opens a "document", all associated rows must be locked, much like Windows locks a file when it is opened. As the "document" may be open until the user chooses to close it, I don't开发者_Go百科 think transactions are a viable solution. The only solution I have come up with is to have a boolean 'Locked' field in every table and to set this to True on relevant rows when a "document" is opened. I'm using SQL Server 2008 R2.

Any ideas?


You can use application locking.


Assuming each document has a unique ID, a portable solution is to use a single table that knows about every locked document:

CREATE TABLE DocumentLocked (
    doc_id INT PRIMARY KEY,
    session_id <some type>,
    lock_acquired DATETIME
);

When you want to lock a document, try to insert the id of the document in question along with some session ID identifying the owning session and the time you locked it. If it fails, the document is already locked. The session ID and lock_acquired columns don't play a role in the locking. It just helps display useful information to the user, like, "This document was locked by Rubio at 9:43 am."

One problem with this approach is that crashed clients can leave documents locked forever, so you need some application-level mechanism to clobber locks. The lock_acquired column can serve as a timeout mechanism by requiring the application to update the time every so often, and using this to detect stale locks.

If you don't care about portability, go with @demas's answer.


In you case "locking" is probably part of your business processes and low-level transaction mechanism should not be used for that purpose. So you're right, you need 'Locked' field either in all participating tables or a single one in a special "lock"-table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜