Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Other SQL Server 2008 Topics
 xp_cmdshell FORFILES Delete old Backup Files

Author  Topic 

Biz1705
Starting Member

8 Posts

Posted - 2011-12-07 : 19:04:53
Dear All,

I have script that works except I can't use @Path in EXEC xp_cmdshell 'FORFILES.
 --Delete Files if backup Successful
EXEC xp_cmdshell 'FORFILES /p @PATH /s /m *.bak* /d -1 /c "CMD /C del /Q /F @FILE"'


Is there a way I can declare my path before and use it with EXEC xp_cmdshell and with FORFILES?

My full code is below
--BACKUP-- WITH NOTIFICATION IF SUCCESSFUL
DECLARE
@FILENAME NVARCHAR(100),
@FILE NVARCHAR(100),
@PATH NVARCHAR(100)= 'E:\SQLBACKUPS\', /* <== Change to suit*/
@NAME NVARCHAR(128),
@SUBJECT NVARCHAR(256),
@BODY NVARCHAR(MAX),
@PROFILE_NAME NVARCHAR(100)

DECLARE db_cursor CURSOR FOR
SELECT [name] FROM sysdatabases WHERE [name] NOT IN ('tempdb')
DECLARE @db NVARCHAR(255),@sql NVARCHAR(1000)
OPEN db_cursor
FETCH NEXT FROM db_cursor
INTO @db
WHILE @@FETCH_STATUS=0
BEGIN

print '@db='+@db

BEGIN TRY
SELECT @FILENAME= @PATH + @db +'_' + DBO.FORMATDATE(GETDATE(),'YY_MM_DD') + '.BAK'
BACKUP DATABASE @db
TO DISK=@FILENAME
WITH FORMAT;
SET @SUBJECT='SQL Success - [' + @@SERVERNAME + ']: Backup Completed_' + DBO.FORMATDATE(GETDATE(),'YY_MM_DD')
SET @BODY='The backup to [' + @FILENAME + '] has completed successfully'
SET @NAME='Backup Monitoring Alert'
SET @PROFILE_NAME = @@servername +'_Profile'
SET @FILE =@db


--Delete Files if backup Successful
EXEC xp_cmdshell 'FORFILES /p @PATH /s /m *.bak* /d -1 /c "CMD /C del /Q /F @FILE"'
END TRY

BEGIN CATCH
SET @SUBJECT='SQL Failure - [' + @@SERVERNAME + ']: Backup Not Completed_' + DBO.FORMATDATE(GETDATE(),'YY_MM_DD')
SET @BODY='Error Message whilst backing up to [' + @FILENAME + '] ' + ERROR_MESSAGE()
SET @NAME='Backup Monitoring Alert'
SET @PROFILE_NAME = @@servername +'_Profile'
END CATCH

-- This will be reached if success or fail
EXECUTE MSDB.DBO.SP_NOTIFY_OPERATOR @PROFILE_NAME, NULL,@NAME,@SUBJECT,@BODY

SELECT @sql=REPLACE(@sql,'|',CHAR(39))
PRINT @sql
EXEC ( @sql )
FETCH NEXT FROM db_cursor INTO @db
END
CLOSE db_cursor
DEALLOCATE db_cursor


Your help would be greatly appreciated.

Biz
   

- Advertisement -