日期:2014-05-18  浏览次数:20513 次

请问一个加行锁的问题?
我想对行数据进行加锁(独占锁):
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 READ

begin tran

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

waitfor delay '00:00:05'

commit tran

B连接中如果执行

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 chp845
select 1,'aa' union all
select 2,'bb'

select * from chp845

id          de
----------- -----
1           aa
2           bb

set 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          aa
2           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工具.