This code lists all disk on an sql serve box with information about size, % free space, cluster size, fragmentation etc. Have only been tested on sql 2005/2008
sp_configure 'show advanced options',1
reconfigure with override
go
sp_configure 'xp_cmdshell',1
reconfigure with override
go
use master
SET NOCOUNT ON
DECLARE @ReturnCode int
declare @TmpString varchar(100)
DECLARE @hr int
DECLARE @fso int
DECLARE @drive char(1)
DECLARE @odrive int
DECLARE @TotalSize varchar(20)
DECLARE @MB bigint ; SET @MB = 1048576
CREATE TABLE #drives (drive char(1) PRIMARY KEY,
FreeSpace int NULL,
TotalSize int NULL,
ClusterSize varchar(100),
Total_fragmentation varchar(100),
File_fragmentation varchar(100))
INSERT #drives(drive,FreeSpace)
EXEC master.dbo.xp_fixeddrives
EXEC @hr=sp_OACreate 'Scripting.FileSystemObject',@fso OUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso
DECLARE dcur CURSOR LOCAL FAST_FORWARD
FOR SELECT drive from #drives
ORDER by drive
OPEN dcur
FETCH NEXT FROM dcur INTO @drive
WHILE @@FETCH_STATUS=0
BEGIN
EXEC @hr = sp_OAMethod @fso,'GetDrive', @odrive OUT, @drive
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso
EXEC @hr = sp_OAGetProperty @odrive,'TotalSize', @TotalSize OUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @odrive
UPDATE #drives
SET TotalSize=@TotalSize/@MB
WHERE drive=@drive
CREATE TABLE #Messages(Message nvarchar(400))
set @TmpString = 'defrag '+@drive +':\ -a -v'
INSERT INTO #Messages
EXEC @ReturnCode = master..xp_cmdshell @TmpString
UPDATE #drives set ClusterSize =(select * from #Messages where message like'%cluster size%')where drive=@drive
UPDATE #drives set Total_fragmentation =(select * from #Messages where message like '%total fragmentation%') where drive=@drive
UPDATE #drives set file_fragmentation = (select top 1 message from #Messages where message like '%file fragmentation%') where drive=@drive
DROP TABLE #Messages
FETCH NEXT FROM dcur INTO @drive
END
CLOSE dcur
DEALLOCATE dcur
EXEC @hr=sp_OADestroy @fso
IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso
SELECT drive,
FreeSpace as 'Free(MB)',
TotalSize as 'Total(MB)',
CAST((FreeSpace/(TotalSize*1.0))*100.0 as int) as 'Free(%)',
ClusterSize,Total_fragmentation,file_fragmentation
FROM #drives
ORDER BY drive
DROP TABLE #drives
No comments:
Post a Comment