Search

Thursday, July 28, 2011

Scripts to check high CPU utilization processes

--Create Temporary table to hold Sysprocesses Records
CREATE TABLE #sp_who2
(SPID INT,
CPUTime INT NULL,
Status VARCHAR(1000) NULL,
Login SYSNAME NULL,
HostName SYSNAME NULL,
BlkBy SYSNAME NULL,
DBName SYSNAME NULL,
Command VARCHAR(1000) NULL,

LastBatch VARCHAR(1000) NULL,
ProgramName VARCHAR(1000) NULL )

--Inserts User SPID with CPU
INSERT INTO #sp_who2
select spid, CPU, Status, convert(sysname, rtrim(loginame)) as loginname , Hostname, blocked, db_name(dbid) as DatabaseName, cmd, Last_batch, Program_name from master.dbo.sysprocesses (nolock)
where spid>50 order by cpu desc

Create Table #SqlStatement(spid int, statement varchar(8000))
create table #temp (x varchar(100), y int, s varchar(1000), id int identity (1,1))

Declare @spid varchar(10)
Declare @Statement varchar(8000)
declare @sql varchar(1000)

DECLARE SpidCursor Cursor
FOR Select spid from #sp_who2
OPEN SpidCursor
FETCH NEXT FROM SpidCursor INTO @spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'dbcc inputbuffer (' + @spid + ')'
insert #temp
exec (@sql)
Insert Into #SqlStatement
Select @spid, s From #Temp where id = (Select max(id) from #Temp)
FETCH NEXT FROM SpidCursor INTO @spid
END
Close SpidCursor
Deallocate SpidCursor

Select B.Statement, A.* from #sp_who2 A Left JOIN #SqlStatement B ON A.spid = B.spid
Drop Table #Temp
Drop Table #SqlStatement
Drop Table #sp_who2

No comments:

Post a Comment