Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Using rowlock & xlock

Author  Topic 

kensai
Posting Yak Master

172 Posts

Posted - 2011-02-02 : 10:07:26
I have a simple job which selects records, inserts them into another table and deletes them from the original table. I want the records to be locked even for reading so I used rowlock and xlock as table hints while selecting them. The thing is I can select said records while the transactions is working. Here's my code:


set transaction isolation level repeatable read;
go

begin try
begin transaction;

insert into myTable2
select * from myTable1 with(rowlock, xlock)
where status = 1;
waitfor delay '00:02:00';
delete from myTable1 where id in(
select id from myTable1 with(rowlock, xlock)
where status = 1
);

commit transaction;
end try
begin catch
if xact_state() <> 0
begin
rollback transaction;
end
end catch;


While the transaction is waiting on WAITFOR line, I can still select the records in another connection. What am I doing wrong?

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-02-02 : 11:58:32
I'm not sure why you would want to block a read on your table. But you could use the TABLOCKX query hint.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-02-02 : 12:02:16
I'm not 100% sure what you are trying to do, but another option might be to DELETE the records first and use an OUTPUT clause to do the insert into Table2.
Go to Top of Page
   

- Advertisement -