侧边栏壁纸
博主头像
健健康康,好好生活博主等级

行动起来,活在当下

  • 累计撰写 17 篇文章
  • 累计创建 20 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

SQL Server锁表会用到的SQL语句

朱顺平
2022-12-21 / 0 评论 / 0 点赞 / 48 阅读 / 3018 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-03-08,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
查询锁表的SQL语句
select  0 as spid,blocked,waittime,cmd, st.text AS SQL_TEXT from (select * from sysprocesses where  blocked>0 ) a
CROSS APPLY sys.dm_exec_sql_text(a.sql_handle) ST
where not exists(select 1 from sysprocesses where  blocked>0 and spid=a.blocked);
查询当前正在执行的SQL明细
SELECT
 der.[session_id],der.[blocking_session_id],
 sp.lastwaittype,sp.hostname,sp.program_name,sp.loginame,sp.spid,
 der.[start_time] AS '开始时间',
 der.[status] AS '状态',
 dest.[text] AS 'sql语句',
 DB_NAME(der.[database_id]) AS '数据库名',
 der.[wait_type] AS '等待资源类型',
 der.[wait_time] AS '等待时间',
 der.[wait_resource] AS '等待的资源',
 der.[logical_reads] AS '逻辑读次数'
 FROM sys.[dm_exec_requests] AS der
 INNER JOIN master.dbo.sysprocesses AS sp ON der.session_id=sp.spid
 CROSS APPLY sys.[dm_exec_sql_text](der.[sql_handle]) AS dest
 -- WHERE [session_id]>50 AND session_id<>@@SPID
 ORDER BY der.[session_id]
 GO
查询具体锁表的SQL
--查询锁表进程
declare @spid int,@bl int,
 @intTransactionCountOnEntry  int,
        @intRowcount    int,
        @intCountProperties   int,
        @intCounter    int
 create table #tmp_lock_who (
 id int identity(1,1),
 spid smallint,
 bl smallint)
 IF @@ERROR<>0 print @@ERROR
insert into #tmp_lock_who(spid,bl) select  0 ,blocked
   from (select * from sysprocesses where  blocked>0 ) a 
   where not exists(select * from (select * from sysprocesses where  blocked>0 ) b 
   where a.blocked=spid)
   union select spid,blocked from sysprocesses where  blocked>0
IF @@ERROR<>0 print @@ERROR 
-- 找到临时表的记录数
 select  @intCountProperties = Count(*),@intCounter = 1
 from #tmp_lock_who
 IF @@ERROR<>0 print @@ERROR 
 if @intCountProperties=0
  select N'现在没有阻塞和死锁信息' as message
-- 循环开始
while @intCounter <= @intCountProperties
begin
-- 取第一条记录
  select  @spid = spid,@bl = bl
  from #tmp_lock_who where Id = @intCounter 
 begin
  if @spid =0 
            select N'引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + N'进程号,其执行的SQL语法如下'
 else
            select N'进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ N'被进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +N'阻塞,其当前进程执行的SQL语法如下'
 DBCC INPUTBUFFER (@bl )
 end 
-- 循环指针下移
 set @intCounter = @intCounter + 1
end
drop table #tmp_lock_who
结束对应PID的SQL
--结束锁表进程
DECLARE
@spid INT
SET @spid = 91--锁表进程
DECLARE
@SQL VARCHAR (1000)
SET @SQL = 'kill ' + CAST (@spid AS VARCHAR) EXEC (@SQL)
0

评论区