简体   繁体   中英

Check if a Table in Sql Server is locked

I 'm writing a windows application which connects to sql server and performs a update action on a table.

Already there is another program named P2 which is altering the data in same table. So the table is locked

I am getting an error while accessing the table from my application

I need a solution in which the program first checks if the table is already locked and if the table is not locked the data has to be updated. If the table is already locked then it has to wait for a while and retry the operation.

Can anyone Provide me one??

It is never a good idea to check if something is locked or not before performing an operation. Because a lock can be acquired just after you perform the check and just before you perform your update:

if(noLockOnTheTable)
{
  // ... something else acquires the lock just at this point
  updateTable();
}

So it's futile to try to check the lock. You should go ahead and try to acquire the lock instead and perform your update right away. You could be avoiding that because the other operation takes too long and you don't want user to wait. In that case you could specify a "short lock wait timeout" and provide user a message saying that "try again later". User doesn't need to wait.

You could try the following:

CREATE TABLE #lockTable
(
[spid] smallint
, [dbid] smallint
, [objid] int
, [indid] smallint
, [type] nchar(4)
, [resource] nchar(32)
, [mode] nvarchar(8)
, [status] nvarchar(5)
);

INSERT INTO #lockTable EXEC sp_lock;

SELECT * FROM #lockTable WHERE objeid = OBJECT_ID('mytable');

DROP TABLE #lockTable;

For example- get locks in current session:

create table dbo.test (i int)
Go    

begin tran
insert into dbo.test With (tablock) (i) values (1)
Go
Select 
    DB_NAME(tl.resource_database_id) database_name, 
    tl.resource_type, 
    case when resource_type = 'OBJECT' then OBJECT_NAME(tl.resource_associated_entity_id) Else null End ObjectName, 
    tl.resource_type, 
    tl.request_mode,
    tl.request_status,
    tl.* 
From sys.dm_tran_locks tl
Where request_session_id = @@SPID 
order by case when resource_type = 'OBJECT' then OBJECT_NAME(tl.resource_associated_entity_id) Else null End,
    tl.request_mode, tl.resource_type
Rollback

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