I need row-level locking

北城余情 提交于 2019-11-29 05:16:33

SQL Server always uses row-level locking by default .... so what exactly is it that you need??

If you lock more than a certain amount of rows (roughly 5000), then SQL Server will do lock escalation (lock the table instead of more than 5000 rows individually) to optimize performance and optimize on resource usage - but that's a good thing! :-)

There are ways to turn this off entirely - but those are NOT recommended! since you're messing with a very fundamental mechanism inside SQL Server's storage engine.

See:

Imagine your system as client-server application, where client and server are connected by very slow line (snail mail for example) and users are modifying their records very long time (a week for example). Then think about, when you need to lock rows/data and when you actually allow changing rows/data and so on - apparently placing SQL server internal locks for days doesn't seem good idea anymore.

If you don't have situation, when two users need to change same record, then you don't need locking while changing data at all. You need locking only for very short moment, when records are changed in database - in other words while user commits changes. (This is optimistic locking scenario.) Of course if two users change same data, then latest changes will overwrite earlier ones.

If you absolutely require that two users should never modify same data (pessimistic locking), then probably most general way is to use some application-defined locks table OR specific field(s) in data table(s). When one user checks some record out (when starting editing or similar), then you need to check, is that record already in use (locked) and if not, then mark this record as locked. Of course you need some functionality to remove stale locks then.

Or use SQL server internal specific functions for such cases. Look here: sp_getapplock function in MSDN; this way you shouldn't worry about records kept locked forever etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!