1. 程式人生 > >sqlserver2008 死鎖解決方法及效能優化方法

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.


執行下面的SQL語句就知道了(下面的語句可以在SQL Server 2005及後續版本中執行,用你的資料庫名替換掉這裡的AdventureWorks):

USE master
go
SELECT 
object_name(dt.OBJECT_ID,db_id('AdventureWorks')) Tablename,
si.name
IndexName,dt.avg_fragmentation_in_percent AS ExternalFragmentation,
dt.avg_page_space_used_in_percent AS InternalFragmentation
FROM
(
	SELECT object_id,index_id,avg_fragmentation_in_percent,avg_page_space_used_in_percent
	FROM sys.dm_db_index_physical_stats (db_id('AdventureWorks'),null,null,null,'DETAILED')
	WHERE index_id <> 0
) AS dt INNER JOIN AdventureWorks.sys.indexes si ON si.object_id=dt.object_id
AND si.index_id=dt.index_id 
AND dt.avg_fragmentation_in_percent>10
AND dt.avg_page_space_used_in_percent<75 
ORDER BY avg_fragmentation_in_percent DESC