SQL SERVER 查询被锁的表、解锁表

查询被锁的表
SELECT
    request_session_id spid,
    OBJECT_NAME( resource_associated_entity_id ) tableName 
    sys.dm_tran_locks 
WHERE
    resource_type = 'OBJECT'
DECLARE @spid INT 
SET @spid = 113 --锁表进程
DECLARE
    @SQL VARCHAR ( 1000 ) 
    SET @SQL = 'kill ' + CAST ( @spid AS VARCHAR ) 
    EXEC ( @SQL )
通过游标循环解锁
-- 释放游标(假如有重名有表的话使用)
DEALLOCATE order_cursor 
-- 游标循环遍历
BEGIN
  -- 定义循环的变量
    DECLARE
        @a INT,@error INT,@temp INT 
        SET @a = 1 
        SET @error = 0 
    -- 定义游标
    DECLARE
        order_cursor CURSOR FOR (SELECT request_session_id FROM sys.dm_tran_locks WHERE resource_type = 'OBJECT' AND  resource_associated_entity_id = '495340829')
        /* 注意:WHERE条件使用OBJECT_NAME( resource_associated_entity_id ) 会报express转int错误;
        这里需要把【表名:TBTHD_PERINFO_ALL】查出来再使用,即'495340829'
    -- 打开游标
    OPEN order_cursor 
    -- 开始循环游标变量
    FETCH NEXT FROM order_cursor INTO @temp
    WHILE
            @@FETCH_STATUS = 0 -- 返回被 FETCH语句执行的最后游标的状态
            BEGIN
            -- 解锁表
            DECLARE
                @SQL VARCHAR ( 1000 ) 
                SET @SQL = 'kill ' + CAST ( @temp AS VARCHAR ) 
                EXEC ( @SQL ) 
                SET @a =@a + 1 
                SET @error = @error + @@ERROR -- 记录每次运行sql后是否正确,0正确
            FETCH NEXT 
                order_cursor INTO @temp -- 转到下一个游标,没有会死循环
            END CLOSE order_cursor -- 关闭游标