SQLServer 并发问题 先select再update

child_1986 2015-08-24 02:38:13
SQLServer 并发问题

例如

并发执行以下两个事务

事务1

begin tran
declare @count int =0
select @count=[Count] from test4 where id=1
select @count as count1
waitfor delay '00:00:30' --等待30秒
update test4 set [Count]=@count+1 where id=1
commit tran

事务2

begin tran
declare @count int =0
select @count=[Count] from test4 where id=1 --holdlock人为加锁
select @count as count2
update test4 set [Count]=@count+1 where id=1
commit tran

要求:事务2的count2是事务1中已经update 加1后的数据

怎么在数据库层面解决

试过锁,总是出现死锁的问题
...全文
584 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
child_1986 2015-08-24
  • 打赏
  • 举报
回复
嗯嗯,谢谢楼上,我也尝试了一下,只能加锁的方式
Tiger_Zhao 2015-08-24
  • 打赏
  • 举报
回复
你没明白我的意思。
避免并发问题,必须一上来就加更新锁
我用 UPDATE/OUTPUT 只是为了省略 SELECT。
如果你一定要分开SELECT/UPDATE,如下:

事务1
begin tran 
declare @count int =0
select @count=[Count] from test4 WITH(UPDLOCK,HOLDLOCK) where id=1
select @count as count1
waitfor delay '00:00:30'
update test4 set [Count]=@count+1 where id=1
commit tran

select * from TEST4

事务2
begin tran
declare @count int =0
select @count=[Count] from test4 WITH(UPDLOCK,HOLDLOCK) where id=1
select @count as count2
update test4 set [Count]=@count+1 where id=1
commit tran

select * from TEST4
gw6328 2015-08-24
  • 打赏
  • 举报
回复
没有看懂题目
child_1986 2015-08-24
  • 打赏
  • 举报
回复
1楼的亲,我可能没写明白,意思只是,update时会使用select出的数据,不一定是+1这样的操作
Tiger_Zhao 2015-08-24
  • 打赏
  • 举报
回复
事务1
begin tran

DECLARE @t TABLE ([Count] int)
declare @count int =0

-- 都在更新、加锁的同时读取旧值
update test4
set [Count]=[Count]+1
OUTPUT DELETED.[Count]
INTO @t
where id=1

waitfor delay '00:00:30'

SELECT @count = [Count] FROM @t
SELECT @count AS count1

commit tran

SELECT * FROM test4

事务2
begin tran

DECLARE @t TABLE ([Count] int)
declare @count int =0

update test4
set [Count]=[Count]+1
OUTPUT DELETED.[Count]
INTO @t
where id=1

SELECT @count = [Count] FROM @t

SELECT @count AS count2

commit tran

SELECT * FROM test4

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧