这个存储过程用于检查trace所在分区的空间大小,如果小于设定的值,则停止保存到这个分区的trace
if exists (select * from dbo.sysobjects where xtype='P' and name ='up_AutoTrace_check')
drop procedure up_AutoTrace_check
go
create procedure dbo.up_AutoTrace_check
@Path varchar(256) ='E:Trace', --路径,用于保存trace文件,必须是绝对路径
@minMBfree int = 50 --最小可用磁盘空间,小于此值则停止trace
--@systemVersion varchar(256) ='chinese' --操作系统版本,如果是英文版,请输入english,默认是简体中文版
/**********
--文件名 :
--用途 :检查磁盘空间,如果可用磁盘空间小于输入的值,则停止所检查分区上的所有的trace
--输入参数 :
--返回值解释 :
--创建者 : summer.yang
--创建日期 : 2005-6-18
--修改者 :
--修改日期 :
--修改注解 :(引用请保留此信息)
--备注说明 :检查输入的路径下是否存在trc文件,用作停止trace的根据
**********/
--创建作业,定期运行
--如果trace保存到表中,则检查不到
--如果保存路径是共享路径,如何检查?
as
set nocount on
set @Path=ltrim(rtrim(@Path))
--------------
--如果不存在trace则退出
if Not exists(SELECT * FROM :: fn_trace_getinfo(0)
where property=2 and convert(char(2),value) like left(@Path,2)+'%'
)
goto finish
--------------
declare @file varchar(26),@tracefile varchar(256)
declare @cmd_sql varchar(4000),@mbfree int,@message varchar(4000)
create table #tbl(dir_file nvarchar(1000) null )
----检查可用空间
/*
D:>freedisk
INFO: 105,071,742,976 bytes free on current volume.
E:>freedisk
信息: 当前卷上有 42,912,407,552 字节可用。
*/
set @cmd_sql = 'FREEDISK '
insert into #tbl(dir_file) exec master.dbo.xp_cmdshell @cmd_sql
select * from #tbl
if (select charindex('INFO:',dir_file,1) from #tbl where dir_file is not null)>0
begin
select @mbfree = cast(replace(substring(dir_file,charindex('INFO',dir_file)+5,charindex('bytes',dir_file,1)
-(charindex('INFO',dir_file)+5)),',','') as bigint)/1024/1024
from #tbl where dir_file is not null
end
else if (select charindex('信息:',dir_file,1) from #tbl where dir_file is not null)>0
begin
select @mbfree = cast(replace(substring(dir_file,charindex('INFO',dir_file)+5,charindex('bytes',dir_file,1)
-(charindex('INFO',dir_file)+5)),',','') as bigint)/1024/1024
from #tbl where dir_file is not null
end
Print '当前磁盘分区"'+ left(@Path,2)+'"的可用空间是: '+ltrim(str(@mbfree))+'MB'+char(10)
if @mbfree <= @minMBfree
begin
declare @traceid int,@activeTraceFile varchar(256)
declare @cursor cursor
set @cursor=cursor forward_only static for
select traceid,convert(varchar(256),value) from :: fn_trace_getinfo(0)
where property=2 and convert(char(2),value) like left(@Path,2)+'%'
open @cursor
fetch next from @cursor into @traceid,@activeTraceFile
while @@fetch_status=0
begin
exec sp_trace_setstatus @traceid, 0 --停止跟踪
exec sp_trace_setstatus @traceid, 2 --关闭跟踪
set @message='由于磁盘分区'+ upper(left(@Path,1))
+'的可用空间低于存储过程up_AutoTrace_check的参数输入值:'+ltrim(str(@minMBfree))
+',已经关闭Trace! '+char(10)
+'此Trace的id为:' +ltrim(str(@traceid))+char(10)
+'保存的trace文件为:' +@activeTraceFile+'.trc'
raiserror (@message,16,1) --with log
fetch next from @cursor into @traceid,@activeTraceFile
end
end
-------------
--删除已经存在的1个月前的trc文件
--set @cmd_sql = 'if exist ' + @tracefile + '.trc ' + 'del ' + @tracefile + '*.trc'
--exec @return = master.dbo.xp_cmdshell @cmd_sql, no_output
finish:
go