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') and
-- UNCOMMENT THIS ONE TO BACKUP ONLY THE ocms_dev db_name(s_mf.database_id) in ('ocms_dev' )
-- ALTERNATIVELY SPECIFY ONLY ONE DB , uncomment this line
-- and db_name(s_mf.database_id) in ('ocms_dev')
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 = @DbName + '_' + replace(convert(varchar, getdate(), 112), '-', '.') + '.bak'
--REMEMBER TO PUT HERE THE TRAILING \ FOR THE DIRECTORY !!!
declare @sqlToRun varchar(4000)
set @sqlToRun = 'BACKUP DATABASE [' + @DBName + '] TO DISK = N''D:\GenApp\DATA\Backups\' +
@DBFileName + ''' WITH NOFORMAT, INIT, NAME = N''' +
@DBName + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 100'
-- debug print @sqlToRun
-- debug return
exec (@sqlToRun )
FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
END
CLOSE DATABASES_CURSOR
DEALLOCATE DATABASES_CURSOR
Help A Big! Thanks, God Bless You.
ReplyDeleteThank you for help. Help me a lot! God Bless You.
ReplyDelete-- to include hh_mm_ss in name
ReplyDeleteset @DBFileName = @DbName + '_' + replace(replace(replace(convert(varchar, getdate(), 120), '-', '_'),' ','_'),':','_') + '.bak'