February 19, 2010 at 8:26 am
I have a bug in an application that seems to crash when it's trying to update a row on a table. I know for a fact that the table is being updated by another application at the same time, which is why it crashes, actually it gives a timeout error.
My boss has asked me to reproduce the problem in the test environment. Is there a way to lock a table for an indeterminate amount of time to simulate the process that's inserting records, while my app is updating?
Thanks!
February 19, 2010 at 8:32 am
sure, here's a basic example.
in any query window with SSMS:
begin tran
select * from example with (tablockx)
the with(TABLOCKX) gives you an excluseive table lock.
now if you try in a second query window to do a select * from example , or with your application, you will see it spin endlessly, or time out due to a connection.
eventually, you'll need to either ROLLBACK or COMMIT your tran, or close the window so SSMS rollsback your tran for you.
Lowell
February 19, 2010 at 8:35 am
You could begin a transaction, update a record and then not commit until you want to end the lock.
February 19, 2010 at 12:51 pm
Lowell, I tried your code but somehow I was able to update data in the locked table.
I tried :
BEGIN TRANSACTION
SELECT * FROM tblMyTable WITH (TABLELOCKX)
and I got an error message:
"TABLELOCKX" is not a recognized table hints option. If it is intended as a parameter to a table-valued function, ensure that your database compatibility mode is set to 90.
Then I tried :
BEGIN TRANSACTION
SELECT* FROM tblMyTable TABLELOCKX
and it executed without error. But I was able to open another window and run an update on the table successfully.
February 22, 2010 at 1:49 pm
Try:
BEGIN TRANSACTION
SELECT* FROM tblMyTable with (TABLOCKX)
MJ
February 23, 2010 at 6:57 am
I wouldn't recommend SELECT * without a WHERE clause for this because it could bring back billions of rows of data. SELECT TOP 1.. will suffice with the TABLOCKX hint. 🙂
What the OP REALLY needs to do however is find out WHY the blocking is happening in the first place. That means evaluating queries for missing indexes and possibly refactoring code to improve query plans and transaction duration.
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply