简体   繁体   English

数据库锁是否需要事务处理?

[英]Do DB locks require transactions?

Is it true that "Every statement (select/insert/delete/update) has an isolation level regardless of transactions"? “每个语句(选择/插入/删除/更新)都具有隔离级别,与事务无关,”是真的吗?

I have a scenario in which I have set update of statements inside a transaction (ReadCommitted). 我有一种情况,其中我设置了事务(ReadCommitted)中的语句更新。 And another set not in a transaction (select statements). 而另一组不在事务中(选择语句)。

  1. In this case when first set is executing another waits. 在这种情况下,当第一组正在执行时,另一个等待。
  2. If I set READ_COMMITTED_SNAPSHOT for DB Deadlock occurs. 如果我为数据库设置READ_COMMITTED_SNAPSHOT,则会发生死锁。

     ALTER DATABASE Amelio SET ALLOW_SNAPSHOT_ISOLATION ON ALTER DATABASE Amelio SET READ_COMMITTED_SNAPSHOT ON 

To solve this problem, do I need to put "Select" statements in TransactionScope? 若要解决此问题,我是否需要在TransactionScope中放置“选择”语句?

On SQL Server every transaction has an implicit or explicit transaction level. 在SQL Server上,每个事务都有一个隐式或显式事务级别。 Explicit if called with BEGIN/COMMIT/ROLLBACK TRANSACTION , implicit if nothing like this is issued. 如果使用BEGIN/COMMIT/ROLLBACK TRANSACTION调用,则是显式的;如果未发布此类内容,则是隐式的。

Start your snapshot before the update query starts. 在更新查询开始之前启动快照。 Otherwise you give SQL Server no chance to prepare the changed rows into tempdb and the Update query still has the lock open. 否则,SQL Server将没有机会将已更改的行准备到tempdb中,并且Update查询仍然具有打开的锁。

Another way without creating a snapshot isolation is to use SELECT <columns> FROM <table> WITH (NOLOCK) which is the way to tell SQL Server to get the rows no matter what (aka READ_UNCOMMITED). 不创建快照隔离的另一种方法是使用SELECT <columns> FROM <table> WITH (NOLOCK) ,这是一种告诉SQL Server无论如何获取行的方法(aka READ_UNCOMMITED)。 As it is a query hint it changes the isolation level even with your settings. 由于它是一个查询提示,即使使用您的设置,它也会更改隔离级别。 Can work if you are not bothered which state of the row is queried - however caution needs to be used when evaluating the data received. 如果您不打扰要查询行的哪个状态,则可以使用-但是在评估接收到的数据时需要谨慎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM