请问一个加行锁的问题?
我想对行数据进行加锁(独占锁):
declare @index int
select @index=currentindex where tablename='t_account'
update t_tableinfo set currentindex=currentindex+1 where tablename='t_account'
请问下,我怎么才能对上面两个sql语句加锁:
我想实现的逻辑是:
我先读出currentindex数据,然后再把currentindex+1更新,并且更行和读取过程中,不可以并其他sql语句读取或者更新,这怎么做呀?
[解决办法]
1 如何锁一个表的某一行A 连接中执行SET TRANSACTION ISOLATION LEVEL REPEATABLE READbegin transelect * from tablename with (rowlock) where id=3waitfor delay '00:00:05'commit tranB连接中如果执行update tablename set colname='10' where id=3 --则要等待5秒update tablename set colname='10' where id<>3 --可立即执行2 锁定数据库的一个表SELECT * FROM table WITH (HOLDLOCK) 注意: 锁定数据库的一个表的区别SELECT * FROM table WITH (HOLDLOCK) 其他事务可以读取表,但不能更新删除SELECT * FROM table WITH (TABLOCKX) 其他事务不能读取表,更新和删除
[解决办法]
set transaction isolation level repeatable
[解决办法]
做个例子,供参考.
create table chp845 (id int, de varchar(5))insert into chp845select 1,'aa' union allselect 2,'bb'select * from chp845id de----------- -----1 aa2 bbset transaction isolation level serializable-- 开始事务begin tran-- 读取id的值. declare @x int select @x=id from chp845(xlock) where id=1--------------------------------连线2中执行查询select * from chp845 where id=1--> 等待..------------------------------ -- 修改id的值. update chp845 set id=id+10 where id=1 --------------------------------连线2中再执行查询select * from chp845 where id=1--> 再等待..------------------------------ -- 提交事务commit tran--------------------------------连线2中再执行查询select * from chp845-- 结果id de----------- -----11 aa2 bb------------------------------
[解决办法]
begin tran update t_tableinfo with(uplock,readpast) commit tran
[解决办法]
想深入了解可用SQL Profiler工具.