读书人

请教一个加行锁的有关问题

发布时间: 2012-01-21 21:31:43 作者: rapoo

请问一个加行锁的问题?
我想对行数据进行加锁(独占锁):
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语句读取或者更新,这怎么做呀?

[解决办法]

探讨
我想对行数据进行加锁(独占锁):
declare @index int
select @index=currentindex where tablename='t_account'
update t_tableinfo set currentindex=currentindex+1 where tablename='t_account'
请问下,我怎么才能对上面两个sql语句加锁:
我想……

[解决办法]
SQL code
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) 其他事务不能读取表,更新和删除
[解决办法]
探讨
SQL code
1 如何锁一个表的某一行

A 连接中执行

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

begin tran

select * from tablename with (rowlock) where id=3

waitfor delay '00:00:05'

commit tran

B连……

[解决办法]
提高事务隔离等级到repeatable即可,
SQL code
set transaction isolation level repeatable
[解决办法]
做个例子,供参考.
SQL code
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------------------------------
[解决办法]
探讨
我想对行数据进行加锁(独占锁):
declare @index int
select @index=currentindex where tablename='t_account'
update t_tableinfo set currentindex=currentindex+1 where tablename='t_account'
请问下,我怎么才能对上面两个sql语句加锁:
我想……

[解决办法]
这样写就可以了,忽略表中锁定行。
SQL code
 begin tran  update t_tableinfo with(uplock,readpast) commit tran
[解决办法]
想深入了解可用SQL Profiler工具.

读书人网 >SQL Server

热点推荐