---
title: "开源项目：高级SQL Server监控、性能图、分析与优化、版本控制"
author: "sabolasi"
date: "2011-12-07T11:49:54Z"
tags: []
categories: ["编程语言"]
slug: "sql-server"
draft: false
lastmod: "2011-12-07T11:49:54Z"
id: 1295334
url: "https://sabolasi.iteye.com/blog/1295334"
---

这是一个相当高级的SQL Server监控工具，全面监控SQL Server的活动与性能，分析性能瓶颈，给出优化建议。

 

red-gate有一个在线的数据库监控工具，不过那个商业的东西价钱不便宜。我写的这个平民版，开源，功能上有颇多的差异（各有长短）。

 

项目在Codeplex上开源：http://sqlmon.codeplex.com/

 

在Codeproject上有英文介绍：http://www.codeproject.com/KB/database/sqlmonitor.aspx

## 介绍

是否想过：“SQL Server为什么那么慢？”，“为什么CPU占用那么高？”，“到底哪里死锁了？”，“为什么数据库那么大？”，“怎样才可以查看我的存储过程和函数的历史版本？”，“可以让我的SQL Server跑得更快吗？”。

 

你的答案就在这里;-)

 

## 到底能干嘛

- 监控SQL Server的活动：进程、任务，详细查看当前执行的语句与实际变量值，终止进程
- IO/CPU/网络等性能趋势图
- 函数/存储过程等的版本控制，这在商业软件中也没有（如果你知道，告诉我）
- 对象浏览器：服务器、数据库、表、视图、函数、存储过程等
- 数据库管理：收缩、日志清除、备份、恢复等
- 在整个数据库中搜索对象/脚本内容，这在SQL Server 2012中也无法做到
- 自动显示所有对象的脚本，如表、视图、函数、存储过程等

 

## 概览

 

![](http://download.codeplex.com/download?ProjectName=sqlmon&DownloadId=188521)

 

在上图中，我们可以看见表的create脚本。如果你选择其它对象，如函数、存储过程等，一样会显示相应的脚本。

 

在对象列表中，如果是数据表，显示表的占用空间（包括索引）、记录数等。

 

这些在SQL Server 2012中都没有。

 

**获取数据库信息**

 

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)View Code

SELECT DB\_NAME(database\_id) AS DatabaseName, Name AS Logical\_Name, Physical\_Name, CAST(size AS decimal(30,0))\*8 AS Size, state FROM sys.master\_files WHERE DB\_NAME(database\_id) = 'YOUR\_DATABASE\_NAME' 

 

**对象/脚本搜索**

 

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)View Code

--search in script  
Select s.name, s.create\_date AS CreateDate, s.modify\_date AS ModifyDate, s.type, c.text from syscomments c left join sys.objects s on c.id = s.object\_id where \[Text] like '%YOUR\_QUERY\_HERE%'

--search in jobs  
SELECT job\_id, name, date\_created AS CreateDate, date\_modified AS ModifyDate, 'Job' AS type FROM msdb.dbo.sysjobs

 

 

**获取表结构**

 

 

--To get table names and records  
SELECT   
    \[TableName] = so.name,   
    \[RowCount] = MAX(si.rows)   
FROM   
    sysobjects so,   
    sysindexes si   
WHERE   
    so.xtype = 'U'   
    AND   
    si.id = OBJECT\_ID(so.name)   
GROUP BY   
    so.name  
\--To get table used space  
EXEC sp\_spaceused 'TABLE\_NAME'  
\--To get table script  
declare @Id int, @i int, @i2 int,@Sql varchar(max),@Sql2 varchar(max), @f1 varchar(5), @f2 varchar(5), @f3 varchar(5), @f4 varchar(5), @T varchar(5)  
    select @Id=object\_id('YOUR\_TABLE\_NAME\_HERE'), @f1 = char(13) + char(10), @f2 = '    ', @f3=@f1+@f2, @f4=',' + @f3  
      
    if not(@Id is null)  
    BEGIN  
    declare @Data table(Id int identity primary key, D varchar(max) not null, ic int null, re int null, o int not null);  
      
    -- Columns  
    with c as(  
        select c.column\_id, Nr = row\_number() over(order by c.column\_id), Clr=count(\*) over(),  
            D = quotename(c.name) + ' ' +  
                case when s.name = 'sys' or c.is\_computed=1 then '' else quotename(s.name) + '.' end +  
                case when c.is\_computed=1 then '' when s.name = 'sys' then t.Name else quotename(t.name) end +  
                case when c.user\_type\_id!=c.system\_type\_id or c.is\_computed=1 then ''  
                    when t.Name in ('xml', 'uniqueidentifier', 'tinyint', 'timestamp', 'time', 'text', 'sysname', 'sql\_variant', 'smallmoney', 'smallint', 'smalldatetime', 'ntext', 'money',  
                                    'int', 'image', 'hierarchyid', 'geometry', 'geography', 'float', 'datetimeoffset', 'datetime2', 'datetime', 'date', 'bigint', 'bit') then ''  
                    when t.Name in('varchar','varbinary', 'real', 'numeric', 'decimal', 'char', 'binary')  
                        then '(' + isnull(convert(varchar,nullif(c.max\_length,-1)), 'max') + isnull(','+convert(varchar,nullif(c.scale, 0)), '') + ')'  
                    when t.Name in('nvarchar','nchar')  
                        then '(' + isnull(convert(varchar,nullif(c.max\_length,-1) / 2), 'max') + isnull(','+convert(varchar,nullif(c.scale, 0)), '') + ')'  
                    else '??'  
                    end +   
                case when ic.object\_id is not null then ' identity(' + convert(varchar,ic.seed\_value) + ',' + convert(varchar,ic.increment\_value) + ')' else '' end +  
                case when c.is\_computed=1 then 'as' + cc.definition when c.is\_nullable = 1 then ' null' else ' not null' end +  
                case c.is\_rowguidcol when 1 then ' rowguidcol' else '' end +  
                case when d.object\_id is not null then ' default ' + d.definition else  '' end  
        from sys.columns c  
        inner join sys.types t  
        on t.user\_type\_id = c.user\_type\_id  
        inner join sys.schemas s  
        on s.schema\_id=t.schema\_id  
        left outer join sys.computed\_columns cc  
        on cc.object\_id=c.object\_id and cc.column\_id=c.column\_id  
        left outer join sys.default\_constraints d  
        on d.parent\_object\_id=@id and d.parent\_column\_id=c.column\_id  
        left outer join sys.identity\_columns ic  
        on ic.object\_id=c.object\_id and ic.column\_id=c.column\_id  
        where c.object\_id=@Id  
          
    )  
        insert into @Data(D, o)  
        select '    ' + D + case Nr when Clr then '' else ',' + @f1 end, 0  
        from c where NOT D IS NULL   
        order by column\_id  
      
    -- SubObjects  
    set @i=0  
    while 1=1  
        begin  
        select top 1 @i=c.object\_id, @T = c.type, @i2=i.index\_id  
        from sys.objects c   
        left outer join sys.indexes i  
        on i.object\_id=@Id and i.name=c.name  
        where parent\_object\_id=@Id and c.object\_id&gt;@i and c.type not in('D')  
        order by c.object\_id  
        if @@rowcount=0 break  
        if @T = 'C'   
            insert into @Data   
            select @f4 + 'check ' + case is\_not\_for\_replication when 1 then 'not for replication ' else '' end + definition, null, null, 10  
            from sys.check\_constraints where object\_id=@i  
        else if @T = 'Pk'  
            insert into @Data   
            select @f4 + 'primary key' + isnull(' ' + nullif(lower(i.type\_desc),'clustered'), ''), @i2, null, 20  
            from sys.indexes i  
            where i.object\_id=@Id and i.index\_id=@i2  
        else if @T = 'uq'  
            insert into @Data values(@f4 + 'unique', @i2, null, 30)  
        else if @T = 'f'  
            begin  
            insert into @Data   
            select @f4 + 'foreign key', -1, @i, 40  
            from sys.foreign\_keys f  
            where f.object\_id=@i  
              
            insert into @Data   
            select ' references ' + quotename(s.name) + '.' + quotename(o.name), -2, @i, 41  
            from sys.foreign\_keys f  
            inner join sys.objects o  
            on o.object\_id=f.referenced\_object\_id  
            inner join sys.schemas s  
            on s.schema\_id=o.schema\_id  
            where f.object\_id=@i  
              
            insert into @Data   
            select ' not for replication', -3, @i, 42  
            from sys.foreign\_keys f  
            inner join sys.objects o  
            on o.object\_id=f.referenced\_object\_id  
            inner join sys.schemas s  
            on s.schema\_id=o.schema\_id  
            where f.object\_id=@i and f.is\_not\_for\_replication=1  
            end  
        else  
            insert into @Data values(@f4 + 'Unknow SubObject \[' + @T + ']', null, null, 99)  
        end

    insert into @Data values(@f1+')', null, null, 100)  
      
    -- Indexes  
    insert into @Data  
    select @f1 + 'create ' + case is\_unique when 1 then 'unique ' else '' end + lower(s.type\_desc) + ' index ' + 'i' + convert(varchar, row\_number() over(order by index\_id)) + ' on ' + quotename(sc.Name) + '.' + quotename(o.name), index\_id, null, 1000  
    from sys.indexes s  
    inner join sys.objects o  
    on o.object\_id=s.object\_id  
    inner join sys.schemas sc  
    on sc.schema\_id=o.schema\_id  
    where s.object\_id=@Id and is\_unique\_constraint=0 and is\_primary\_key=0 and s.type\_desc != 'heap'  
      
    -- columns  
    set @i=0  
    while 1=1  
        begin  
        select top 1 @i=ic from @Data where ic&gt;@i order by ic   
        if @@rowcount=0 break  
        select @i2=0, @Sql=null, @Sql2=null  
        while 1=1  
            begin  
            select @i2=index\_column\_id,   
                @Sql = case c.is\_included\_column when 1 then @Sql else isnull(@Sql + ', ', '(') + cc.Name + case c.is\_descending\_key when 1  then ' desc' else '' end end,  
                @Sql2 = case c.is\_included\_column when 0 then @Sql2 else isnull(@Sql2 + ', ', '(') + cc.Name + case c.is\_descending\_key when 1  then ' desc' else '' end end  
            from sys.index\_columns c  
            inner join sys.columns cc  
            on c.column\_id=cc.column\_id and cc.object\_id=c.object\_id  
            where c.object\_id=@Id and index\_id=@i and index\_column\_id&gt;@i2  
            order by index\_column\_id  
            if @@rowcount=0 break  
            end  
        update @Data set D=D+@Sql +')' + isnull(' include' + @Sql2 + ')', '') where ic=@i  
        end  
          
    -- references  
    set @i=0  
    while 1=1  
        begin  
        select top 1 @i=re from @Data where re&gt;@i order by re  
        if @@rowcount=0 break  
          
        select @i2=0, @Sql=null, @Sql2=null  
        while 1=1  
            begin  
            select @i2=f.constraint\_column\_id,   
                @Sql = isnull(@Sql + ', ', '(') + c1.Name,  
                @Sql2 = isnull(@Sql2 + ', ', '(') + c2.Name  
            from sys.foreign\_key\_columns f  
            inner join sys.columns c1  
            on c1.column\_id=f.parent\_column\_id and c1.object\_id=f.parent\_object\_id  
            inner join sys.columns c2  
            on c2.column\_id=f.referenced\_column\_id and c2.object\_id=f.referenced\_object\_id  
            where f.constraint\_object\_id=@i and f.constraint\_column\_id&gt;@i2  
            order by f.constraint\_column\_id  
            if @@rowcount=0 break  
            end  
        update @Data set D = D + @Sql + ')'  where re=@i and ic=-1  
        update @Data set D = D + @Sql2 + ')'  where re=@i and ic=-2  
        end;  
      
    -- Render  
    with x as(  
        select id=d.id-1, D=d.D + isnull(d2.D,'')  
        from @Data d  
        left outer join @Data d2  
        on d.re=d2.re and d2.o=42  
        where d.o=41  
          
    )  
    update @Data  
        set D=d.D+x.D  
    from @Data d  
    inner join x  
    on x.id=d.id  
      
    delete @Data where o in(41, 42)  
      
    select @Sql = 'create table ' + quotename(s.name) + '.' + quotename(o.name) + '(' + @f1  
    from sys.objects o  
    inner join sys.schemas s  
    on o.schema\_id = s.schema\_id  
    where o.object\_id=@Id  
      
    set @i=0  
    while 1=1  
        begin  
        select top 1 @I=Id, @Sql = @Sql + D from @Data order by o, case when o=0 then right('0000' + convert(varchar,id),5)  else D end, id  
        if @@rowcount=0 break  
        delete @Data where id=@i  
        end  
    END  
    SELECT @Sql

 

 

## 性能趋势图

 

![](http://download.codeplex.com/Download?ProjectName=sqlmon&DownloadId=309058)

 

在上图中，我们可以看见SQL Server历史/当前的IO/CPU/网络信息都在趋势图中显示。

 

这些数据来自几个系统变量：

 

- @@cpu\_busy
- @@io\_busy
- @@idle
- @@pack\_received
- @@pack\_sent
- @@connections
- @@packet\_errors
- @@total\_read
- @@total\_write
- @@total\_errors

 

 以下是相应的SQL：

 

declare @now         datetime  
declare @cpu\_busy     int  
declare @io\_busy    int  
declare @idle        int  
declare @pack\_received    int  
declare @pack\_sent    int  
declare @pack\_errors    int  
declare @connections    int  
declare @total\_read    int  
declare @total\_write    int  
declare @total\_errors    int

declare @oldcpu\_busy     int    /* used to see if DataServer has been rebooted \*/  
declare @interval    int  
declare @mspertick    int    /* milliseconds per tick \*/

/*  
\**  Set @mspertick.  This is just used to make the numbers easier to handle  
\**  and avoid overflow.  
\*/  
select @mspertick = convert(int, @@timeticks / 1000.0)

/*  
\**  Get current monitor values.  
\*/  
select  
    @now = getdate(),  
    @cpu\_busy = @@cpu\_busy,  
    @io\_busy = @@io\_busy,  
    @idle = @@idle,  
    @pack\_received = @@pack\_received,  
    @pack\_sent = @@pack\_sent,  
    @connections = @@connections,  
    @pack\_errors = @@packet\_errors,  
    @total\_read = @@total\_read,  
    @total\_write = @@total\_write,  
    @total\_errors = @@total\_errors

/*  
\**  Check to see if DataServer has been rebooted.  If it has then the  
\**  value of @@cpu\_busy will be less than the value of spt\_monitor.cpu\_busy.  
\**  If it has update spt\_monitor.  
\*/  
select @oldcpu\_busy = cpu\_busy  
    from master.dbo.spt\_monitor  
if @oldcpu\_busy &gt; @cpu\_busy  
begin  
    update master.dbo.spt\_monitor  
        set  
            lastrun = @now,  
            cpu\_busy = @cpu\_busy,  
            io\_busy = @io\_busy,  
            idle = @idle,  
            pack\_received = @pack\_received,  
            pack\_sent = @pack\_sent,  
            connections = @connections,  
            pack\_errors = @pack\_errors,  
            total\_read = @total\_read,  
            total\_write = @total\_write,  
            total\_errors = @total\_errors  
end

/*  
\**  Now print out old and new monitor values.  
\*/  
set nocount on  
select @interval = datediff(ss, lastrun, @now)  
    from master.dbo.spt\_monitor  
/* To prevent a divide by zero error when run for the first  
\** time after boot up  
\*/  
if @interval = 0  
    select @interval = 1  
select last\_run = lastrun, current\_run = @now, seconds = @interval,  
    cpu\_busy\_total = convert(int, ((@cpu\_busy * @mspertick) / 1000)),  
    cpu\_busy\_current = convert(int, (((@cpu\_busy - cpu\_busy)  
        * @mspertick) / 1000)),  
    cpu\_busy\_percentage = convert(int, ((((@cpu\_busy - cpu\_busy)  
        * @mspertick) / 1000) * 100) / @interval),  
    io\_busy\_total = convert(int, ((@io\_busy * @mspertick) / 1000)),  
    io\_busy\_current = convert(int, (((@io\_busy - io\_busy)  
        * @mspertick) / 1000)),  
    io\_busy\_percentage = convert(int, ((((@io\_busy - io\_busy)  
        * @mspertick) / 1000) * 100) / @interval),  
    idle\_total = convert(int, ((convert(bigint,@idle) * @mspertick) / 1000)),  
    idle\_current = convert(int, (((@idle - idle)  
        * @mspertick) / 1000)),  
    idle\_percentage = convert(int, ((((@idle - idle)  
        * @mspertick) / 1000) * 100) / @interval),  
    packets\_received\_total = @pack\_received,  
    packets\_received\_current = @pack\_received - pack\_received,  
    packets\_sent\_total = @pack\_sent,  
    packets\_sent\_current = @pack\_sent - pack\_sent,  
    packet\_errors\_total = @pack\_errors,  
    packet\_errors\_current = @pack\_errors - pack\_errors,  
    total\_read = @total\_read,  
    current\_read = @total\_read - total\_read,  
    total\_write = @total\_write,  
    current\_write =    @total\_write - total\_write,  
    total\_errors = @total\_errors,  
    current\_errors = @total\_errors - total\_errors,  
    connections\_total = @connections,  
    connections\_current = @connections - connections  
from master.dbo.spt\_monitor

/*  
\**  Now update spt\_monitor  
\*/  
update master.dbo.spt\_monitor  
    set  
        lastrun = @now,  
        cpu\_busy = @cpu\_busy,  
        io\_busy = @io\_busy,  
        idle = @idle,  
        pack\_received = @pack\_received,  
        pack\_sent = @pack\_sent,  
        connections = @connections,  
        pack\_errors = @pack\_errors,  
        total\_read = @total\_read,  
        total\_write = @total\_write,  
        total\_errors = @total\_errors

 

 

## 版本控制

数据库开发人员总在想，每次修改了函数/存储过程，我们都得自己做备份，用以历史参考，当发现错误的时候，可以回滚。在SQL Monitor里面，这个是全自动的。

 

版本控制的思想来自这里：http://www.sqlteam.com/article/using-ddl-triggers-in-sql-server-2005-to-capture-schema-changes

 

原理就是用数据库DDL触发器记录每个DDL操作，自增版本，并存储到一个表中。

 

![](http://download.codeplex.com/Download?ProjectName=sqlmon&DownloadId=284310)

 

**关键代码** 

 

 

SET ANSI\_NULLS OFF  
GO  
SET QUOTED\_IDENTIFIER OFF  
GO  
SET ANSI\_NULLS ON  
GO  
SET QUOTED\_IDENTIFIER ON  
GO  
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object\_id = OBJECT\_ID(N'\[dbo].\[VERSION\_CONTROL\_TABLE]') AND type in (N'U'))  
BEGIN  
CREATE TABLE \[dbo].\[{0}](  
    \[ID] \[bigint] IDENTITY(1,1) NOT NULL,  
    \[databasename] \[varchar](256) NULL,  
    \[eventtype] \[varchar](50) NULL,  
    \[objectname] \[varchar](256) NULL,  
    \[objecttype] \[varchar](25) NULL,  
    \[sqlcommand] \[nvarchar](max) NULL,  
    \[loginname] \[varchar](256) NULL,  
    \[hostname] \[varchar](256) NULL,  
    \[PostTime] \[datetime] NULL,  
    \[Version] \[int] NOT NULL,  
 CONSTRAINT \[PK\_VERSION\_CONTROL\_TABLE] PRIMARY KEY CLUSTERED   
(  
    \[ID] ASC  
)WITH (IGNORE\_DUP\_KEY = OFF) ON \[PRIMARY]  
) ON \[PRIMARY]  
END

GO

SET ANSI\_NULLS ON  
GO  
SET QUOTED\_IDENTIFIER ON  
GO

CREATE TRIGGER \[TRG\_VERSION\_CONTROL\_TABLE}]  
ON DATABASE  
FOR CREATE\_PROCEDURE, ALTER\_PROCEDURE, DROP\_PROCEDURE,  
CREATE\_TABLE, ALTER\_TABLE, DROP\_TABLE,  
CREATE\_FUNCTION, ALTER\_FUNCTION, DROP\_FUNCTION,  
CREATE\_TRIGGER, ALTER\_TRIGGER, DROP\_TRIGGER,  
CREATE\_VIEW, ALTER\_VIEW, DROP\_VIEW,  
CREATE\_INDEX, ALTER\_INDEX, DROP\_INDEX

AS

SET NOCOUNT ON

DECLARE @CurrentVersion int  
DECLARE @CurrentID int  
DECLARE @DatabaseName varchar(256)  
DECLARE @ObjectName varchar(256)  
DECLARE @data XML

SET @data = EVENTDATA()

INSERT INTO dbo.VERSION\_CONTROL\_TABLE(databasename, eventtype,objectname, objecttype, sqlcommand, loginname,Hostname,PostTime, Version)  
VALUES(  
@data.value('(/EVENT\_INSTANCE/DatabaseName)\[1]', 'varchar(256)'),  
@data.value('(/EVENT\_INSTANCE/EventType)\[1]', 'varchar(50)'),  -- value is case-sensitive  
@data.value('(/EVENT\_INSTANCE/ObjectName)\[1]', 'varchar(256)'),   
@data.value('(/EVENT\_INSTANCE/ObjectType)\[1]', 'varchar(25)'),   
@data.value('(/EVENT\_INSTANCE/TSQLCommand)\[1]', 'varchar(max)'),   
@data.value('(/EVENT\_INSTANCE/LoginName)\[1]', 'varchar(256)'),  
HOST\_NAME(),  
GETDATE(),  
0  
)

SET @CurrentID = IDENT\_CURRENT('VERSION\_CONTROL\_TABLE')  
SELECT @DatabaseName = databasename, @ObjectName = objectname FROM VERSION\_CONTROL\_TABLE WHERE ID = @CurrentID  
IF (@DatabaseName IS NOT NULL AND @ObjectName IS NOT NULL)  
BEGIN  
    SELECT @CurrentVersion = MAX(Version) FROM VERSION\_CONTROL\_TABLE WHERE databasename = @DatabaseName AND objectname = @ObjectName  
    UPDATE VERSION\_CONTROL\_TABLE SET Version = ISNULL(@CurrentVersion, 0) + 1 WHERE ID = @CurrentID  
END  
GO  
ENABLE TRIGGER \[TRG\_VERSION\_CONTROL\_TABLE] ON DATABASE

 

 

SQL Monitor会全自动给你的所有脚本修改做版本记录。你可以随时查看在什么时候哪个机器用什么身份修改了哪个对象的脚本。

 

![](http://download.codeplex.com/Download?ProjectName=sqlmon&DownloadId=284847)

 

SQL Monitor内置版本比较，你可以清楚知道不同的版本的差异。 

 

 

## 活动监控

 

 

![](http://download.codeplex.com/download?ProjectName=sqlmon&DownloadId=188522)

 

上图清晰显示所有系统的活动进程，每个进程当前执行什么语句。

 

**获取进程列表**

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)View Code

--To get processes  
SELECT s.session\_id AS spid, s.login\_time, s.host\_name AS hostname, s.host\_process\_id AS hostprocess, s.login\_name AS loginname, s.logical\_reads AS physical\_io, s.cpu\_time AS cpu, s.program\_name, 0 AS dbid, s.last\_request\_start\_time AS last\_batch\_begin, CASE WHEN status = 'running' THEN GETDATE() ELSE dateadd(ms, s.cpu\_time, s.last\_request\_end\_time) END AS last\_batch\_end, s.status FROM sys.dm\_exec\_sessions s JOIN sys.dm\_exec\_connections c ON s.session\_id = c.session\_id

 

 

**获取任务列表**

 

![](http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)View Code

--To get jobs  
SELECT job\_id AS spid, name AS program\_name, 0 AS dbid, 0 AS cpu, 0 AS physical\_io, NULL AS login\_time, NULL AS last\_batch\_begin, NULL AS last\_batch\_end, NULL AS status, NULL AS hostname, NULL AS hostprocess, NULL AS cmd, NULL AS loginname FROM msdb.dbo.sysjobs

 

 

## 分析

这是商业级的数据与性能分析，SQL Monitor自动给你的系统、数据库、数据表、索引等进行分析。

 

 

![](http://download.codeplex.com/Download?ProjectName=sqlmon&DownloadId=309059)

 

基本原理是首先利用master.sys.xp\_fixeddrives获取磁盘的剩余空间，然后：

 

 

//database & disk free space  
        var databases = GetDatabasesInfo();  
        var files = new List&lt;tuple&lt;bool, /&gt;&gt;();  
        databases.AsEnumerable().ForEach(d =&gt;  
        {  
            var database = GetDatabaseInfo(d\["name"].ToString());  
            database.AsEnumerable().ForEach(f =&gt;  
            {  
                files.Add(new Tuple&lt;bool, /&gt;(Convert.ToInt32(f\["type"]) == 1, f\["physical\_name"].ToString(), Convert.ToInt64(Convert.ToDecimal(f\["Size"]) / Size1K)));  
            }  
            );  
        });  
        var spaces = new Dictionary&lt;string, /&gt;&gt;();  
        //MB free  
        var driveSpaces = Query("EXEC master.sys.xp\_fixeddrives");  
        driveSpaces.AsEnumerable().ForEach(s =&gt;  
        {  
            //could not use name but rather index, because the column name will change according to locale  
            spaces.Add(s\[0].ToString(), new KeyValue&lt;long, /&gt;(Convert.ToInt64(s\[1]), 0));  
        });  
        files.ForEach(f =&gt;  
        {  
            //maybe some access issues  
            try  
            {  
                var drive = f.Item2.Substring(0, 1);  
                if (spaces.ContainsKey(drive))  
                {  
                    spaces\[drive].Value += f.Item3;  
                }  
            }  
            catch (Exception)  
            {  
                //mmmm.....what can we do, mate?  
            }  
        });  
        spaces.ForEach(s =&gt;  
        {  
            if (s.Value.Key &lt; s.Value.Value / 100 * Settings.Instance.DatabaseDiskFreeSpaceRatio)  
            {  
                analysisResult.Add(new AnalysisResult { ResultType = AnalysisResultTypes.DiskFreeSpace, ObjectName = s.Key, ReferenceValue = s.Value.Key, CurrentValue = s.Value.Value, Factor = Settings.Instance.DatabaseDiskFreeSpaceRatio + SizePercentage });  
            }  
        });

        //database data file & log file space  
        databases.AsEnumerable().ForEach(d =&gt;  
        {  
            var name = d\["name"].ToString();  
            if (!systemDatabases.Contains(name))  
            {  
                var database = GetDatabaseInfo(name);  
                var databaseSpace = new Dictionary&lt;databasefiletypes, /&gt; { { DatabaseFileTypes.Data, 0 }, { DatabaseFileTypes.Log, 0 } };  
                database.AsEnumerable().ForEach(f =&gt;  
                {  
                    var key = (DatabaseFileTypes)Convert.ToInt32(f\["type"]);  
                    databaseSpace\[key] += Convert.ToInt64(Convert.ToDecimal(f\["Size"]) / Size1K);  
                }  
                );  
                bool? shrink = null;  
                if (databaseSpace\[DatabaseFileTypes.Log] &gt; databaseSpace\[DatabaseFileTypes.Data] / 100 * Settings.Instance.DatabaseDataLogSpaceRatio)  
                    shrink = false;  
                else  
                {  
                    var logSpaces = SQLHelper.Query("DBCC SQLPERF(LOGSPACE)", GetServerInfo(name));  
                    var logSpace = logSpaces.Select(string.Format("\[Database Name] = '{0}'", name));  
                    if (logSpace.Length &gt; 0)  
                    {  
                        var logSpacedUsed = Convert.ToDouble(logSpace\[0]\["Log Space Used (%)"]);  
                        if (logSpacedUsed &lt; Settings.Instance.DatabaseDataLogSpaceRatio)  
                            shrink = true;  
                    }  
                }  
                if (shrink != null)  
                    analysisResult.Add(new AnalysisResult { ResultType = AnalysisResultTypes.DatabaseLogSpace, ObjectName = name, ReferenceValue = databaseSpace\[DatabaseFileTypes.Log], CurrentValue = databaseSpace\[DatabaseFileTypes.Data], Factor = Settings.Instance.DatabaseDataLogSpaceRatio + SizePercentage, Key = (bool)shrink ? 1 : 0 });  
            }  
        });

 

对于表空间，使用了sp\_spaceused，关键代码：

 

var tables = GetObjects(KeyTables);  
tables.AsEnumerable().ForEach(t =&gt;  
    {  
        var name = t\[KeyName].ToString();  
        var space = Query(string.Format("EXEC sp\_spaceused '{0}'", name), CurrentServerInfo);  
        if (space.Rows.Count &gt; 0)  
        {  
            var row = space.Rows\[0];  
            var dataSize = ToKB(row\["data"]) / Size1K;  
            var indexSize = ToKB(row\["index\_size"]) / Size1K;  
            if (indexSize &gt; dataSize / 100 * Settings.Instance.TableDataIndexSpaceRatio)  
                analysisResult.Add(new AnalysisResult { ResultType = AnalysisResultTypes.TableIndexSpace, ObjectName = name, ReferenceValue = dataSize, CurrentValue = indexSize, Factor = Settings.Instance.DatabaseDataLogSpaceRatio + SizePercentage, Key = (int)TableIndexSpaceRules.DataIndexSpaceRatio });  
        }  
    });

 

 

![](http://download.codeplex.com/download?ProjectName=sqlmon&DownloadId=188523)

 

 

## 最新版本

 

http://sqlmon.codeplex.com/releases/view/77943