Saturday, 20 October 2012

Check All SQL Server Database or Individual File I/O stall stats

--
-- step 1: over all view across all databases

SELECT    DB_NAME(fs.database_id) AS [Database Name]
        ,ms.name as LogicName
        ,ms.type_desc
        ,io_stall/1000./3600. as [io_stall_hr]
        ,CAST((io_stall_read_ms + io_stall_write_ms)/(num_of_reads + num_of_writes) AS NUMERIC(10,1)) AS [avg_io_stall_ms] 
        ,num_of_reads + num_of_writes AS [total_io]
        ,num_of_reads
        ,num_of_writes
        ,CAST(io_stall_read_ms/(case when num_of_reads=0 then 1 else 0.0 end + num_of_reads) AS NUMERIC(25,2)) AS [avg_read_stall_ms]
        ,CAST(io_stall_write_ms/(case when num_of_writes=0 then 1.0 else 0.0 end +num_of_writes) AS NUMERIC(25,2)) AS [avg_write_stall_ms]
        ,io_stall_read_ms
        ,io_stall_write_ms
        ,io_stall_read_ms + io_stall_write_ms AS [io_stalls]
        ,fs.file_id
FROM    sys.dm_io_virtual_file_stats(null,null) fs inner join sys.master_files ms
        on ms.database_id=fs.database_id and ms.file_id=fs.file_id
--WHERE    (num_of_reads + num_of_writes)>0
WHERE    (num_of_reads + num_of_writes)>10
--ORDER BY (io_stall) desc;
ORDER BY avg_io_stall_ms DESC;

--
-- step 2: check each database individually
-- temp db i/o or any other database wait stat
-- switch to any database and run stat for that db
SELECT
    DB_NAME(fs.database_id)    as    [Database]
    ,f.[Name]                  as    [LogicName]
    ,f.[filename]              as    [FileName]
    ,cast((fs.[size_on_disk_bytes]+0.00) / 1024 /1024 as decimal(25,2)) as    [Size(MB)]
    -- this seems to be off! data could be written by dropped later
    -- this is NOT space used
    ,cast((fs.[num_of_bytes_written]+0.00)/1024/1024 as decimal(25,2)) as    [TotalWrite(MB)]
    ,cast((fs.[io_stall_write_ms]+0.00)/fs.[num_of_writes] as decimal(25, 2)) as [AverageWriteDelay(ms)]
    -- deal with 0 write or read case
    ,cast(1024.00*1024*fs.[io_stall_write_ms]/(case when fs.[num_of_bytes_written]=0 then 1 else fs.[num_of_bytes_written] end) as decimal(25, 2)) as [AverageWrite Delay(ms/MB)]
    ,cast((fs.[num_of_bytes_read]+0.00)/1024/1024 as decimal(25, 2)) as    [TotalRead(MB)]
    ,cast((fs.[io_stall_read_ms]+0.00)/(case when fs.[num_of_reads]=0 then 1 else fs.[num_of_reads] end) as decimal(25, 2)) as [AverageReadDelay(ms)]
    ,cast(1024.00*1024*fs.[io_stall_read_ms]/(case when fs.[num_of_bytes_read]=0 then 1 else fs.[num_of_bytes_read] end) as decimal(25, 2)) as [AverageReadDelay(ms/MB)]
    ,fs.[num_of_writes]
    ,fs.[num_of_reads]
    --,fs.*
    FROM    -- 2(tempdb database id), NULL(all the files related to tempdb)
            --sys.dm_io_virtual_file_stats(2, NULL) fs inner join sys.sysfiles f
            -- current database
            sys.dm_io_virtual_file_stats(db_id(), NULL) fs inner join sys.sysfiles f
            on fs.file_id = f.fileid
    WHERE [num_of_writes]>0 OR [num_of_reads]>0
    order by 3--,6

No comments:

Post a Comment