sqlserver2008 死锁解决方法及性能优化方法
关于死锁:
sp_who active –看看哪个引起的死锁, blk里面即阻塞的spid;
dbcc inputbuffer(@blk) — 可以查看是那个sql语句造成的死锁;
sp_lock –看看锁住了那个资源,objid即被锁住的资源id;
select object_name(objid) 可得到受影响的表名;
综合以上功能,我们可以写一个自动查找死锁的存储过程,如下:
查找死锁.sql
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE Find_Lock AS BEGIN SET NOCOUNT ON; declare @spid int,@blk int DECLARE cur CURSOR FOR 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 OPEN cur FETCH NEXT FROM cur INTO @spid,@blk WHILE @@FETCH_STATUS = 0 begin if @spid =0 select ‘ 引起死锁的进程号是 : ‘+ CAST(@blk AS VARCHAR(10)) + ‘, 其执行的 SQL 语法如下 ‘ else select ‘ 进程号 SPID : ‘+ CAST(@spid AS VARCHAR(10))+ ‘ 被 ‘ + ‘ 进程号 SPID : ‘+ CAST(@blk AS VARCHAR(10)) +’ 阻塞 , 其当前进程执行的 SQL 语法如下 ‘ DBCC INPUTBUFFER (@blk ) FETCH NEXT FROM cur INTO @spid,@blk end CLOSE cur DEALLOCATE cur END GO
sqlserver性能优化
go
exec sp_configure ”awe enabled”,”1″–内存可以支持64g
exec sp_configure ”lightweight pooling”,”0″–不使用nt纤程
exec sp_configure ”priority boost”,”1″–增加sqlserver优先级
exec sp_configure ”network packet size (b)”,”8192″–增加sqlserver网络包的大小
reconfigure with override
–优化数据库设置
declare @currentdatabase sysname
select @currentdatabase = db_name((select dbid from master.dbo.sysprocesses wherespid = @@spid))
exec sp_dboption @currentdatabase, ‘select into/bulkcopy’, ‘true’ –对大容量数据操作不记录日志
exec sp_dboption @currentdatabase, ‘trunc. log on chkpt.’, ‘true’ –自动截断日志
exec sp_dboption @currentdatabase, ‘auto create statistics’, ‘true’–自动创建统计
exec sp_dboption @currentdatabase, ‘auto update statistics’, ‘true’–自动更新统
go
如果你不做日常维护,请立即开始。
经常用 DBCC showcontig(表名) 查看表的碎片, 主要查看扫描密度 ,如果主要的大表扫描密度 < 40%, 意味着你有严重的碎片可以用DBCC indexDefrag (数据库名,表名)整理碎片或者用DBCC DBREINDEX(表名) 重建 index.
查看阻塞情况: 等待类型为LCK_M_S:“当某任务正在等待获取共享锁时出现”
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
SELECT wt.blocking_session_id AS BlockingSessesionId ,sp.program_name AS ProgramName ,COALESCE(sp.LOGINAME, sp.nt_username) AS HostName ,ec1.client_net_address AS ClientIpAddress ,db.name AS DatabaseName ,wt.wait_type AS WaitType ,ec1.connect_time AS BlockingStartTime ,wt.WAIT_DURATION_MS/1000 AS WaitDuration ,ec1.session_id AS BlockedSessionId ,h1.TEXT AS BlockedSQLText ,h2.TEXT AS BlockingSQLText FROM sys.dm_tran_locks AS tl INNER JOIN sys.databases db ON db.database_id = tl.resource_database_id INNER JOIN sys.dm_os_waiting_tasks AS wt ON tl.lock_owner_address = wt.resource_address INNER JOIN sys.dm_exec_connections ec1 ON ec1.session_id = tl.request_session_id INNER JOIN sys.dm_exec_connections ec2 ON ec2.session_id = wt.blocking_session_id LEFT OUTER JOIN master.dbo.sysprocesses sp ON SP.spid = wt.blocking_session_id CROSS APPLY sys.dm_exec_sql_text(ec1.most_recent_sql_handle) AS h1 CROSS APPLY sys.dm_exec_sql_text(ec2.most_recent_sql_handle) AS h2;