1. 程式人生 > 其它 >SQL_資料庫死鎖問題

SQL_資料庫死鎖問題

1.查詢被鎖程序

SELECT spid 被鎖程序ID, 
	blocked 鎖程序ID,
	status 被鎖狀態, 
	login_time 登入時間, 
	SUBSTRING(SUSER_SNAME(sid),1,30) 被鎖程序登陸帳號, 
	SUBSTRING(hostname,1,12) 被鎖程序使用者機器名稱, 
	SUBSTRING(DB_NAME(dbid),1,13) 被鎖程序資料名稱, 
	cmd 被鎖程序命令, 
	waittype 被鎖程序等待型別
FROM master.sys.sysprocesses 
WHERE SPID>50 and blocked!=0 AND spid<>blocked 
order by waittime desc 

2.查詢堵塞源型別

SELECT 
	CASE	
		WHEN waittime!=0X0000 AND open_tran>=0 AND status='runnable' THEN N'執行時間太長' 
		WHEN waittime=0X0000 AND open_tran>0 AND status='sleeping' THEN N'sleeping程序事物未提交' 
		WHEN waittime in(0x0800,0x0063) AND open_tran>=0 AND status='runnable' THEN N'沒有及時取走結果集' 
		WHEN waittime=0X0000 AND open_tran>0 AND status='rollback' THEN N'超時或主動回滾' 
		WHEN waittime>=0X0000 AND open_tran>=0 AND status='runnable' THEN N'死鎖以堵塞體現' 
	END AS Reason,
	b.text SQL,
	DB_NAME(a.dbid) as DB,
	program_name,
	hostname,
	loginame
FROM master.sys.sysprocesses a CROSS APPLY sys.dm_exec_sql_text(a.sql_handle) b 
WHERE SPID=450
--這裡的where條件中的SPID就是被鎖程序ID。另外需要記錄鎖程序的SQL語句,之後優化這個SQL語句。
--KILL 450     就是直接殺死這個程序,解決鎖的問題 

3.查詢回話資訊

select s.session_id,s.status,s.login_time,s.host_name,
	s.program_name,s.host_process_id,s.client_version,
	s.client_interface_name,s.login_name,s.last_request_start_time,
	s.last_request_end_time,c.connect_time,c.net_transport,
	c.net_packet_size,c.client_net_address,r.request_id,r.start_time,
	r.status,r.command,r.database_id,r.user_id,r.blocking_session_id,
	r.wait_type,r.wait_time,r.last_wait_type,r.wait_resource,
	r.open_transaction_count,r.transaction_id,r.percent_complete,
	r.cpu_time,r.reads,r.writes,r.granted_query_memory
from sys.dm_exec_requests r
right outer join sys.dm_exec_sessions s on r.session_id=s.session_id
right outer join sys.dm_exec_connections c on s.session_id=c.session_id
where s.is_user_process=1