简体   繁体   中英

Checking if a table in sql server is locked with SET LOCK_TIMEOUT 0

Basically I need to check if a table is locked from my code.

I know if I run this directly on the DB;

SELECT * FROM 'tablename' SET LOCK_TIMEOUT 0

I can get an immediate error if a table is locked or none if it isn't. However when I call this statement from my code it still seems to wait for a period of time for the lock to be released before returning. The code I'm using to call this query is;

SqlConnection conn = new SqlConnection(@"ConnectionString");
using(conn)
{
    conn.Open();
    var query = new SqlCommand("SELECT * FROM tablename SET LOCK_TIMEOUT 0", conn);

    try
    {
        SqlDataReader reader = query.ExecuteReader();
        // No lock
    }catch (Exception)
    {
        // Deal with lock exception
    }
} 

I'd like to know straight away. Any suggestions? Or any better ways of doing this?

目前尚不清楚您要达到的目标和目的,但是要在SELECT 之后设置锁定超时,而您需要在SELECT 之前设置锁定超时。

If you mean transaction lock, check this:

select
  object_name(resource_associated_entity_id) as 'TableName' ,*
from
  sys.dm_tran_locks
where resource_type = 'OBJECT'
  and resource_database_id = DB_ID() and 
  object_name(resource_associated_entity_id) = N'YourTableName'

This will return no rows if table is not locked by any transaction

Maybe something like this:

select
  object_name(resource_associated_entity_id) as 'TableName' ,*
from
  sys.dm_tran_locks
where resource_type = 'OBJECT'
  and resource_database_id = DB_ID()

This will get you all tables that tables that is looked at the moment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM