WITH(ROWLOCK)在Update中的使用

The use of WITH (ROWLOCK) in Update

我有一个 .NET 工作流应用程序,每天有 100 个用户使用。此工作流引用 table,其中工作流状态 ID 正在更新。更新语句使用 rowlock.

我在 SP 中的更新语句:

update table1 set statuid = a.statId from table2 a with (rowlock) where  ID = @ids

我的问题是:此更新真的需要 rowlock 吗?数据库不能自动处理吗?

在这种情况下你不需要 rowlock

update table1 set statuid = a.statId from table2 a where ID = @ids

但是,您的示例 SQL 语句假设 statIdtable2 中只有 1 个值。

编辑:

你在评论中说:

there can be multiple values in statuid in table2. However the ids is unique at given point of time

我仍然认为 rowlock 不是必需的,但为了安全起见,您应该从表 2 中获取 id 的最大值。

update table1 set statuid = (select max(statId) from table2) where ID = @ids