I'm setting up a new way to create and delete backups in our internal environments. The space on the servers is a big issue so i really have to find a way to do a backup and delete the older one for each database, procedurally.
I came up with the idea of using the sp_MSforeachdb and simply do a backup. On success, it would delete the older backup that was done the day before. (we do 1 backup per night).
DECLARE @DBOPurpose Varchar(15)
DECLARE @Drive Varchar(1)
Set @DBOPurpose = 'Omnilabs'
DECLARE @command varchar(Max)
Select @command = '
If Exists (Select *
from sys.databases
where name like ''%?''
and name like ''%'+@DBOPurpose+'%'')
BEGIN
EXECUTE master.dbo.xp_create_Subdir '+@Drive+':\SQLBACKUP\'+@DBOPurpose+'
GO
BACKUP DATABASE [?] TO DISK = '+@Drive+':\SQLBackup\'+@DBOPurpose+'_Select Cast(Cast(Year(Getdate())As Varchar(150))+''_''+Cast(month(Getdate())As Varchar(150))+''_''+Cast (Day(Getdate()) As Varchar(150))+''_''+ cast(DATEPART(hour, GETDATE()) as varchar) + '''' + cast(DATEPART(minute, GETDATE()) as varchar)+ '''' + cast(DATEPART(Second, GETDATE()) as varchar)+ ''.bak'' As varchar(150))
END
Print N''TEST''
'
--Select @Command
EXEC sp_MSforeachdb @command
I was expecting that doing Select @Command would actually show me something, but its null. When I run this, it simply writes "Commands completed successfully." within a second, which doesn't make any sense.
Just saw my error, which was only caused by the hyphens that were not placed correctly. Here's the code: