Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic filename for SQL Server backups?

How can you insert the date in the filename (a dynamic filename) used in a T-SQL backup script? Using SQL Enterprise Manager to create and schedule a backup job, I'd like to edit the T-SQL created to change the filename of the backed up database to be dbname_date.bak (i.e. northwind_5-1-2009.bak). The next time the backup runs, it will be northwinds_new_date.bak.


2 Answers

basically what you want to do is declare a string variable, set it to the name and then append the date to the end of the variable. then just use the variable where the name of the backup goes

declare @backupname nvarchar(100)
set @backupname = 'northwind_' + getdate() + '.bak'

something like that should work. you might have to sat the getdate() to nvarchar.

like image 167
DForck42 Avatar answered May 16 '26 05:05

DForck42


Here's what you really want to know - don't reinvent the wheel. Here's a fantastic script to automate backups that does what you're describing:

https://ola.hallengren.com/

like image 30
Brent Ozar Avatar answered May 16 '26 05:05

Brent Ozar