日期:2014-05-17 浏览次数:20589 次
Use master
Go
if object_ID('[sp_DelTargetFile]') is not null
Drop Procedure [sp_DelTargetFile]
Go
Create Procedure sp_DelTargetFile
(
@Dir NVarchar(4000),
@IncludeSubDir bit, --0不包含子目录 1 包含子目录
@FileName NVarchar(4000),
@ModifyBeginTime datetime, --从【最后修改时间】开始
@ModifyEndTime datetime --从【最后修改时间】结束
)
As
Set Nocount On
Declare @Cmd nvarchar(2000),
@OutputInfo nvarchar(2000),
@Path nvarchar(2000),
@File nvarchar(512),
@Date datetime
Declare @Tmp Table(id int Identity(1,1) Primary Key,OutputInfo nvarchar(2000))
Set @Cmd='Dir/t:w/a:-d/4'
If @IncludeSubDir =1
Set @Cmd=@Cmd+'/S'
Set @Cmd=@Cmd+' '+Rtrim(@Dir)+Rtrim('\'+@FileName)
Insert Into @Tmp Exec xp_cmdshell @Cmd
Declare cur_For Cursor For
Select OutputInfo From @Tmp Where Patindex('%/%',OutputInfo)>0 Or Patindex('%\%',OutputInfo)>0
Open cur_For
Fetch Next From cur_For Into @OutputInfo
While @@Fetch_Status=0
Begin
If Patindex('%\%',@OutputInfo)>0
Set @Path=Substring(@OutputInfo,1,Len(@OutputInfo)-Charindex(Char(32),Reverse(@OutputInfo)))+'\'
Else
Begin
Set @Date=Substring(@OutputInfo,1,11) --+Right(Substring(@OutputInfo,1,20),5)+Replace(Replace(Substring(@OutputInfo,11,4),'と','AM'),N'と','PM')
If @Date Between @ModifyBeginTime And @ModifyEndTime
Begin
Set @OutputInfo=Stuff(@OutputInfo,1,20,'')
Set @OutputInfo=Stuff(@OutputInfo,1,Patindex('%[0-9]%',@OutputInfo)-1,'')
Set @File=Stuff(@OutputInfo,1,Charindex(Char(32),@OutputInfo),'')
Set @Cmd='Del '+@Path+'"'+@File+'" '
Exec xp_cmdshell @Cmd ,No_Output
Print N'成功删除文件:'+@Path+@File
End
End
Fetch Next From cur_For Into @OutputInfo
End
CLose cur_For
Deallocate cur_For
Go