Reputation: 7026
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??
Upvotes: 2
Views: 4936
Reputation: 2266
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
Upvotes: 0
Reputation: 47660
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.
Upvotes: 3
Reputation: 9552
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;
Upvotes: 2