简体   繁体   English

检查Sql Server中的表是否被锁定

[英]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. 我正在编写一个Windows应用程序,该应用程序连接到sql server并在表上执行更新操作。

Already there is another program named P2 which is altering the data in same table. 已经有另一个名为P2的程序正在更改同一表中的数据。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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