Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Lock a table manually for some minutes [duplicate]

I know this will be strange, but I want to trigger an error in my MVC application and this error will be based on a LINQ Query, where I would like to get one record from a table. While this record will be blocked (database/table/row) level using T-SQL commands (for example an infinite loop always updating this one record) then my LINQ Query will execute a query to read that record. When LINQ tries then the result should be a time out after 20-30 seconds, anybody has tried this before?

like image 508
Richárd Baldauf Avatar asked Aug 12 '14 20:08

Richárd Baldauf


People also ask

Does @transactional lock table?

Transaction concepts and locks are different. However, transaction used locks to help it to follow the ACID principles. If you want to the table to prevent others to read/write at the same time point while you are read/write, you need a lock to do this.

Can we apply loop in SQL?

In SQL Server, there is no FOR LOOP. However, you simulate the FOR LOOP using the WHILE LOOP.


1 Answers

If I understand your question correctly, it sounds like you would like to force a table lock for purposes of testing. To do that with SQL Server, you can create and run a stored procedure that will cause an exclusive table lock on the table of interest. While that lock is active, you can run the program you want to test.

The following stored procedure should lock your table for 2 minutes. You can change the delay parameter to suit your needs.

BEGIN TRAN   SELECT TOP (1) 1 FROM TABLE WITH (TABLOCKX) WAITFOR DELAY '00:02:00'  ROLLBACK TRAN    GO  

A general approach for doing this was described in the stackoverflow post below. The MSDN link provides some additional information on the WAITFOR statement.

Original stackoverflow post

Supplementary MSDN post

Hope it helps.

like image 113
Marty Avatar answered Sep 24 '22 11:09

Marty