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 SUCCESSFULDECLARE@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_cursorFETCH NEXT FROM db_cursorINTO @dbWHILE @@FETCH_STATUS=0BEGINprint '@db='+@dbBEGIN 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 TRYBEGIN 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 failEXECUTE 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 @dbENDCLOSE db_cursorDEALLOCATE db_cursor
Your help would be greatly appreciated.Biz