在测试环境进行sqlserver锁表测试

将某表设置X锁1分钟:

begin tran
select top 1 * from tableName with (tablockx)
waitfor delay '00:01:00'
commit tran

查询当前被锁的表:

--查询锁表的事务ID,被锁表名,锁模式,客户端主机名,客户端程序名,客户端IP地址
select tl.request_session_id as [事务ID],
       object_name(tl.resource_associated_entity_id) as [被锁表名],
       tl.request_mode as [锁模式],
       es.host_name as [客户端主机名],
       es.program_name as [客户端程序名],
       ec.client_net_address as [客户端IP地址]
from sys.dm_tran_locks as tl
join sys.dm_exec_sessions as es
on tl.request_session_id = es.session_id
join sys.dm_exec_connections as ec
on es.session_id = ec.session_id --或者 on tl.request_owner_id = ec.connection_id
where tl.resource_type = 'OBJECT' --只查表级别的锁
and tl.request_mode in ('X','IX') --只查排他锁和意向排他锁

解锁:

declare @spid  int 
Set @spid  = 57 --锁表进程
declare @sql varchar(1000)
set @sql='kill '+cast(@spid  as varchar)
exec(@sql)

你可能感兴趣的:(sqlserver,数据库)