Add date to SQL database backup filename

DECLARE @MyFileName varchar(1000)

SELECT @MyFileName = (SELECT '\\ServerToSave\Path\MyDB_' + convert(varchar(500),GetDate(),112) + '.bak') 

BACKUP DATABASE [myDB] TO DISK=@MyFileName ...

Try this.

DECLARE @MyFileName varchar(50)
SELECT '\\ServerToSave\Path\MyDB_' + convert(nvarchar(20),GetDate(),112) + '.bak'
BACKUP DATABASE [myDB] TO DISK=@MyFileName ...

The 112 in the Convert gives you the YYYYMMDD format


If you want to include the date and time, so you can use:

DECLARE @MyFileName varchar(200)
SELECT @MyFileName='\\ServerToSave\Path\MyDB_' + REPLACE(convert(nvarchar(20),GetDate(),120),':','-') + '.bak'
BACKUP DATABASE [myDB] TO DISK=@MyFileName ...

The 120 in the Convert gives you the yyyy-mm-dd hh:mi:ss(24h)

The REPLACE function is necessary because the filename can not have the : character.


Use the following

DECLARE @BackupFileName varchar(20)

SELECT @BackupFileName = '\\ServerName\SharedFolder\DatabaseName_' + CONVERT (VarChar, GetDate(), 112) + '.bak'

BACKUP DATABASE [myDB] TO  DISK = @BackupFileName WITH NOFORMAT, INIT,  NAME = N'myDB', SKIP, REWIND, NOUNLOAD,  STATS = 10

Read up on Cast and Convert here http://msdn.microsoft.com/en-us/library/ms187928.aspx

Tags:

Sql

Sql Server