'updlock'에 해당되는 글 1건

  1. UPDLOCK

UPDLOCK

어제 SQL Tag 채팅도중에 오랜만에 UPDLOCK에 대해서 논의했다. 정리해보았다.

UPDLOCK 정의


UPDLOCK : 테이블을 읽는 중 공유 잠금 대신 업데이트 잠금을 사용하며 명령문이나 트랜잭션이 끝날 때까지 보유됩니다. UPDLOCK을 사용하면 다른 트랜잭션이 읽는 것을 차단하지 않고 데이터를 읽을 수 있고 마지막으로 읽은 후 데이터가 변경되지 않으며 나중에 업데이트할 수 있습니다.


TEST(민석형 Test Script)


use test
go
-- Trace flag 3604 is to print the output in query window
-- Trace flag 1200 get a detailed report of all locks acquired by each SQL statement 
DBCC TRACEOFF(3604,1200) WITH NO_INFOMSGS 
go 

if object_id ('tblx') is not null 
drop table tblx 
go 

create table tblx 
(idx int 
,c1 int 
) 
go 

create clustered index cl_tblx on tblx (idx) 
go 

insert into tblx values (1,1) 
insert into tblx values (2,2) 
go 

select * from tblx 
go 

if @@trancount > 0 
rollback tran 
go 

DBCC TRACEON(-1,3604,1200) WITH NO_INFOMSGS
go 

-- session 1
declare @c1 int 
set @c1 = 0 

begin tran 

select @c1 = c1 from tblx with(updlock) where idx =1 

print @c1

update tblx set c1 = c1+1 
where idx =1 

waitfor delay '00:00:005' 
commit
go

-- session 2
declare @a int 
set @a = 0 
begin tran 
select @a =c1 from tblx with(updlock) where idx =1 
print @a 
go



예전에 UPDLOCK을 써서 사용했던 기억이 난다. 그때는 잠금이 오래 걸려 잠금 대기 상태에서 timeout이 발생했던 기억이 난다. 내부적으로 사용하는 SP중에 잠금을 많이 잡아 먹는 로직이 있어서 잠금 타임아웃 흑흑...  


참고자료

UPDLOCK 힌트를 사용 하는 경우 PRB: 교착 상태가 발생할 수 있습니다.
http://support.microsoft.com/kb/179362/ko
Introduction to Locking in SQL Server
http://sqlindian.com/2012/07/06/deadlock-due-to-parallelism/ 
http://www.sqlteam.com/article/introduction-to-locking-in-sql-server

'Transact-SQL' 카테고리의 다른 글

DirtyPage DMV  (0) 2012.10.11
relog 사용 방법  (0) 2012.09.28
group by 빨리 처리하기  (0) 2012.09.11
How to Recycle SQL Server error logs – 5 Types of logs  (1) 2012.09.03
ORIGINAL_LOGIN() 와 SUSER_SNAME() 차이  (0) 2012.07.30