
Those of you looking for a simple backup setup for your SQL server 2005 databases are in luck! I’ve stumbled across this script, and modified it to work for me in my environment.
I am not suggesting that your entire SQL server backup strategy should be to create backup files from your databases nightly. However, a nightly backup scripted to an alternate location is absolutely a crucial component of your SQL server backup strategy.
Use SQL Server Agent to create and schedule a job containing the following code as the command portion of the only step the job will contain:
DECLARE @DBName varchar(255)
DECLARE @DATABASES_Fetch int
DECLARE DATABASES_CURSOR CURSOR FOR
select
DATABASE_NAME = db_name(s_mf.database_id)
from
sys.master_files s_mf
where
– ONLINE
s_mf.state = 0
– Only look at databases to which we have access
and has_dbaccess(db_name(s_mf.database_id)) = 1
– Not master, tempdb or model
and db_name(s_mf.database_id) not in (’Master’,'tempdb’,'model’)
group by s_mf.database_id
order by 1
OPEN DATABASES_CURSOR
FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
declare @DBFileName varchar(256)
set @DBFileName = datename(dw, getdate()) + ‘ – ‘ +
replace(replace(@DBName,’:',’_'),’\',’_')
exec (’BACKUP DATABASE [' + @DBName + '] TO DISK = N”c:\db backup\’ +
@DBFileName + ”’ WITH NOFORMAT, INIT, NAME = N”’ +
@DBName + ‘-Full Database Backup”, SKIP, NOREWIND, NOUNLOAD, STATS = 100′)
FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
END
CLOSE DATABASES_CURSOR
DEALLOCATE DATABASES_CURSOR
Edit the line which contains c:\db backup\ to point at the location where you would like the database backup files to be deposited.
Modify the line with datename(dw, getdate()) in it to change the output file name of your database backups. If you leave the above script unchanged, your database backup files will be named: Monday – dbname.bak, Tuesday – dbname.back etc. In my case, I chose to leave this naming convention for one particular reason. I schedule the SQL Server Agent job to run a few hours before I schedule a task in Windows to execute a batch file which copies the contents of my backup directory to a network file server. By keeping all of my files named using days of the week as the only delimiting factor, I know that my file server will never have more than 7 days worth of data saved onto it (since every Monday will overwrite every past Monday, and every Tuesday will overwrite every past Tuesday, etc).
1 Comment »