且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 SQL Server 中,如何以类似于 Oracle 的“SELECT FOR UPDATE WAIT"的方式锁定单行?

更新时间:2023-01-31 14:10:25

在 SQL Server 中有锁定提示,但它们不像您提供的 Oracle 示例那样跨越它们的语句.在 SQL Server 中执行此操作的方法是在包含要执行的语句的事务上设置隔离级别.请参阅此 MSDN 页面,但总体结构如下所示:>

In SQL Server there are locking hints but they do not span their statements like the Oracle example you provided. The way to do it in SQL Server is to set an isolation level on the transaction that contains the statements that you want to execute. See this MSDN page but the general structure would look something like:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

BEGIN TRANSACTION;

    select * from ...

    update ...

COMMIT TRANSACTION;

SERIALIZABLE 是最高的隔离级别.请参阅其他选项的链接.来自 MSDN:

SERIALIZABLE is the highest isolation level. See the link for other options. From MSDN:

SERIALIZABLE 指定以下内容:

SERIALIZABLE Specifies the following:

语句无法读取已修改但尚未修改的数据由其他事务提交.

Statements cannot read data that has been modified but not yet committed by other transactions.

没有其他事务可以修改已被读取的数据当前事务直到当前事务完成.

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

其他事务不能插入具有键值的新行落入当前任何语句读取的键范围内事务直到当前事务完成.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.