Backup ALL your SQL Server 2005 databases using ONE script

I wanted to backup all my databases... I had loads, creating a step for each db was getting tedious, so I wrote this script.

Enjoy

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

Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

kilgner_t said:

super handi. thanx

13/Dec/2007 17:18 PM

Jack V said:

Thanks , using it with our internal dbs

21/Dec/2007 11:56 AM

Rob Mahon said:

Nice one!

07/Jan/2008 16:58 PM

Calvin said:

Thanks for the script.

You may want also to take a look at 3rd party solution for sql databases backup that I personally use in our company. It's LiteSpeed.

It's not only much easier than different handcoded scripts but can really speed up all backup and restore processes.

For example, after implementing litespeed in our environment database restoring time became several time less than before that really reduced so expensive server downtime.

http://www.scriptlogic.com/products/litespeed/

22/Feb/2008 12:54 PM

Jason Ward said:

Can you tell me under what terms I can use and copy this code? i.e. what license you grant.

Thanks

26/Feb/2008 14:50 PM

phayman said:

No license, you can freely use the code

11/Mar/2008 07:54 AM

Amardeep Rana said:

Thanks Man,

You save my time 2 Hours perday. Offffffffff , Thanks Thanks

12/Sep/2008 17:11 PM

phayman said:

You're welcome Amardeep! Saves me a bunch of time too

12/Sep/2008 17:46 PM

Manatix said:

Hello ALL:

Thank you so much for this script. Pure genius! I found several others, but I decided to combine, what I think, are quite a few good additions and changes. I created a stored procedure. You can of course strip that out for making it into a T-SQL Script job.

Enjoy!

Anthony Urwin

Manatix Technologies B.V.

http://www.manatix.com

/$$$$$$$$$$$$$$$$$$$$$$$$ COPY FROM HERE $$$$$$$$$$$$$$$$$$$$$/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: <Anthony N. Urwin>

-- Company: Manatix Technologies B.V.

-- Website: http://www.manatix.com

-- Create date: <14-09-2008>

-- Description: <This is a simple stored procedure to backup all databases on a SQL server instance>

-- =============================================

ALTER PROCEDURE BackupSQLDatabases

AS

BEGIN

/$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$/

/* Declarations & Variables */

DECLARE @path VARCHAR (500) /* Path of the Backup Files */

DECLARE @folderdate VARCHAR (75) /* The subdir for my backups with Format YYYYMMDD */

DECLARE @cmd VARCHAR (4000) /* The command to create Subdir */

DECLARE @DBName varchar(255)

DECLARE @DATABASES_Fetch int

DECLARE @PreciceDateTime varchar(255)

DECLARE @ServerName varchar(50)

DECLARE @NetworkBackupShare varchar(75)

/$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$/

--Network or local disk path you wish to use, such as D:\Backup

SET @NetworkBackupShare = N'D:\Backup'

/$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$/

--Create a dynamic path for the backup of the databases based on datetime

/$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$/

EXEC sp_configure 'show advanced options', 1;

RECONFIGURE;

EXEC sp_configure 'xp_cmdshell', 1;

RECONFIGURE;

/* gives us YYYYMMDD

hour hh

minute mi, n

second ss, s

*/

SELECT @folderdate = CONVERT(VARCHAR(20), GETDATE(), 112) N'-' N'H' CONVERT(VARCHAR(20), DATEPART(hour, GETDATE()), 112) N'M' CONVERT(VARCHAR(20), DATEPART(minute, GETDATE()), 112) N'S' + CONVERT(VARCHAR(20), DATEPART(second, GETDATE()), 112)

--PRINT @folderdate

/Get Server name/

SET @ServerName = (SELECT @@servername)

/* Path as C:\Backup\YYYYMMDD */

SET path = NetworkBackupShare N'\' ServerName N'\' folderdate + N'\'

/* Create the command that will do the creation of the folder*/

SET cmd = N'mkdir ' + path

--PRINT @cmd

/* Create the new directory */

EXEC master.dbo.xp_cmdshell @cmd , no_output

/* now I can direct all the backup file to the created subdirectory like,

SET filename = path [other_variable/s] ‘.BAK‘ */

/*******************************************/

--Now let's actually do the backups to the path created above

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,':','_'),'\','_') + '.BAK'

        PRINT @path

    exec ('BACKUP DATABASE [' + @DBName + '] TO DISK = ''' + @path + 

        @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

/*******************************************/

EXEC sp_configure 'xp_cmdshell', 0;

EXEC sp_configure 'show advanced options', 0;

RECONFIGURE

END

/$$$$$$$$$$$$$$$$$$$$$$$$ COPY TO HERE $$$$$$$$$$$$$$$$$$$$$/

14/Sep/2008 14:29 PM

Yordan Georgiev said:

::BackUpAllMyDatabases.cmd

:: COMMAND LINE BATCH SCRIPT FOR TAKING BACKUP OF ALL DATABASES

::RUN THE SQL SCRIPT VIA THE COMMAND LINE WITH LOGGING

sqlcmd S localhost -e -i "BackUpAllMyDatabases.sql" o Result_Of_BackUpAllMyDatabases.log

::VIEW THE RESULTS

Result_Of_BackUpAllMyDatabases.log

::pause

29/Nov/2008 10:34 AM

sprike said:

I am newbe, so dumb. Do you a a script to do a single database. Don't ask but, I need to backup an old SQL 7 database that was restored onto SQL 2005 and the Management Studio Management Maintenance Plans do not like SQL 7 so will not automatically backup and add the date and time to the end of the backup file. So it keeps overwriting the same file. Problem if external backup misses for a night.

06/Jan/2009 01:12 AM

Shital Kasliwal said:

Thanks Sir, It's nice one For Backup.

  Thanks Again.
28/Apr/2009 08:33 AM

isaac said:

Hi, I am from Bolivia, Thanks for your script. here script is for toll 'litespeed', I modific your codex, thank a lot.

DECLARE @DBName varchar(255)

DECLARE @DATABASES_Fetch int

DECLARE DATABASES_CURSOR CURSOR FORWARD_ONLY 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, model or msdb

    and db_name(s_mf.database_id) not in ('Master','tempdb','model','msdb')

    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,':','_'),'\','_')*/

declare @rawScript nvarchar(4000)

set @rawScript = '

exec master.dbo.xp_backup_database

database = N[' DBName '],

@backupname = NDatabase Backup,

@desc = NFull Backup ,

@compressionlevel = 1,

filename = NC:\MSSQL\[' DBName ']{0}.bak,

@with = NSKIP,

@with = NSTATS = 10'

declare @appendDate nvarchar(1024)

set @appendDate = '_' + left(replace(replace(replace(convert(nvarchar, getdate(), 120), '-', ), ':', ), ' ', ''), 12)

declare @script nvarchar(4000)

set script = replace(rawScript, '{0}', @appendDate)

exec (@script)

FETCH NEXT FROM DATABASES_CURSOR INTO @DBName

END

CLOSE DATABASES_CURSOR

DEALLOCATE DATABASES_CURSOR

19/Jun/2009 21:34 PM

chitra said:

Hi ,

Thanks a lot .. Its Really helped me a lot .... Nice...

15/Dec/2009 07:39 AM

chitra said:

Hi ,

Thanks a lot .. Its Really helped me a lot .... Nice...

15/Dec/2009 07:39 AM

Zahid said:

thanks dude, its so handy

09/Jan/2010 12:29 PM

CoderXMan said:

Great script!

Question - the script works very well manually. I tried to automate with with sqlcmd to no avail. Has anyone automated this script? I know you can automate and schedule the the management studio but you have to set a schedule for each individual database and I have quite a few. It would be nice to get it all done in one shot like this script does when you run it manually.

-CoderXMan

10/Jun/2010 15:39 PM

phayman said:

Hi CoderXMan,

I run this from SQL Agent and it backs up all databases. Are you saying that it only backs up one?

Paul

10/Jun/2010 15:48 PM

CoderXMan said:

No, It does back up all databases when I run it manually. I am just looking for a way to automate it to make sure I get good backups.

When you backup this way it will also get a good backup of databases that are open on in use, correct?

-CoderXMan

10/Jun/2010 16:01 PM

Marco said:

Muchas Gracias!!

28/Jul/2010 15:31 PM

owen said:

I created a batch file as a scheduled task to run each night on my web server. The batch file is:

sqlcmd S [servername/instance] -i "c:\backupscript.sql"

This works for me!

04/Aug/2010 10:43 AM

CoderXMan said:

I have been using your script for awhile now and it has been working very well. The only thing is I notice my databases were growing out of control over 150 GB's. From what I can gather it is because the transaction logs are not being purged. Do you have any code you can add to this that will back up the *.trn files also to purge these out of the databases?

Thank you,

CoderXMan

13/Sep/2010 19:53 PM

Weng said:

Thank you Paul. You're a time-saver..

23/Aug/2011 05:06 AM

hermanjunge said:

Thank you.

You save me a lot of work.

Haj

03/Sep/2011 20:32 PM

sen said:

Hi,

Excellent Script My dear friend.

Thanks a lot

07/Sep/2011 06:34 AM

sen said:

Nice Code. It helped me a lot.

12/Sep/2011 09:56 AM

Ranathilaka said:

Very usefull script, thx!

Got it to work with your help.

I need to backup Database in to my Tape. how can i change the code. pls help.

thans

30/Sep/2011 04:57 AM

ranathilaka said:

Hi

SELECT @folderdate = CONVERT(VARCHAR(20), GETDATE(), 112) N'-' N'H' CONVERT(VARCHAR(20), DATEPART(hour, GETDATE()), 112) N'M' CONVERT(VARCHAR(20), DATEPART(minute, GETDATE()), 112) N'S' + CONVERT(VARCHAR(20), DATEPART(second, GETDATE()), 112)

SET path = NetworkBackupShare N'\' ServerName N'\' folderdate + N'\'

gives error. pls correct

30/Sep/2011 05:50 AM

Mishel said:

Gr8888 work!!!!

14/Nov/2011 09:14 AM

Chris said:

Really good work !

19/Dec/2011 19:06 PM

HaiPLS said:

Thank all you so much!

04/Aug/2012 10:04 AM

MOHIT CHAUHAN said:

Gr888888888888888888888888888 work MANNNNNNNNNNN!!!!

THANK YOU ,THANK'S A LOT

12/Oct/2012 10:49 AM

Praveen said:

This is wonderful script.. It is helping me in taking backup of all my SQL DBs in a single shot.

13/Mar/2013 06:46 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.