-- This script will take a backup of all databases that you define in the @database variable -- The path will define where the .bak files will be put -- The postname will add a string to the end of all the files, this is used if you take multiple backups of the same databases -- Stats defines if it will display stats in the messagetab while doing the backup
-------------------------------------------------------------------------------------------------------------
-- This script will take a backup of all databases that you define in the @database variable
-- The path will define where the .bak files will be put
-- The postname will add a string to the end of all the files, this is used if you take multiple backups of the same databases
-- Stats defines if it will display stats in the messagetab while doing the backup
--------------------------------------------------------------------------------------------------------------
DECLARE @Databases nvarchar(1000)-- database1,database2,database3
DECLARE @Path nvarchar(1000) -- x:\folderone\folder2\
Declare @PostName nvarchar(20) -- 0001
DECLARE @WithStats bit
--SET @Databases = 'DM,DM_TEST'
SET @Databases = 'Mydatabase,Mydatabase2'
SET @Path = 'x:\folderone\folder2\'
SET @PostName = '_0001'
SET @WithStats = 'True'
DECLARE @AmountOfDatabase int
SET @AmountOfDatabase = len(@Databases) - len(replace(@Databases, ',', '')) + 1
DECLARE @loop int SET @loop = 1
DECLARE @DatabaseName nvarchar(200) SET @DatabaseName = ''
DECLARE @DatabaseNameSql nvarchar(1000) SET @DatabaseNameSql = ''
DECLARE @BackupString nvarchar(1000) SET @BackupString = ''
WHILE (@loop <= @AmountOfDatabase)
begin
SET @DatabaseNameSql = @DatabaseNameSql + ' DECLARE @xml xml SET @xml = ''<split><el>' + replace(@Databases,',','</el><el>') + '</el></split>'''
SET @DatabaseNameSql = @DatabaseNameSql + ' select @el = split.el.value(''.'',''varchar(max)'') from @xml.nodes(''/split/el[string-length(.)>0][position() = ' + CONVERT(nvarchar,@loop) + ']'') split(el)'
EXEC sp_executesql @DatabaseNameSql, N'@el nvarchar(200) OUTPUT', @DatabaseName OUT;
Print('----------------------' + @DatabaseName + '---------------------------------')
Print('Beginning backup on database ' + Convert(nvarchar, @loop) + '/' + Convert(nvarchar, @AmountOfDatabase))
SET @BackupString = @BackupString + ' BACKUP DATABASE ' + @DatabaseName + ' TO DISK = ''' + @Path + @DatabaseName + @PostName + '.bak'''
SET @BackupString = @BackupString + ' WITH INIT'
IF @WithStats = 'True'
SET @BackupString = @BackupString + ', STATS'
EXEC(@BackupString)
SET @DatabaseName = ''
SET @DatabaseNameSql = ''
SET @BackupString = ''
SET @loop = @loop + 1
end