How to backup all SQL Server Databases in SQL Server - SQL Server Tutorial

Scenario:

You are working as SQL Server DBA or Developer. You need to take backup of all the databases from SQL Server Instance.  The backups should be created with date_time.

The below script can be used to take full backup of all the databases from SQL Server Instance, Also you can change Select query which returns list of databases to include or exclude databases from backup.


 USE MASTER
GO
DECLARE @BackupPath varchar(100)
--Provide the backup path 
SET @BackupPath = 'C:\BackupFolderPath\'
DECLARE @DatabaseName AS varchar(128)

DECLARE Cur CURSOR FOR
--Change the select query for the DBs you like to backup
SELECT
  name
FROM sys.databases
WHERE name NOT IN ('TempDB', 'model')

OPEN Cur
FETCH NEXT FROM Cur INTO @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE @SQL varchar(max) = NULL
  DECLARE @DBNamewithDateTime varchar(128) = NULL
  SET @DBNamewithDateTime = @DatabaseName + '_' + REPLACE(CAST(GETDATE()
       AS date), '-', '') + '_' + REPLACE(CAST(CAST(GETDATE() AS time
       AS char(8)), ':', '')

  SET @SQL = 'BACKUP DATABASE [' + @DatabaseName + '] TO  DISK = N''' +
              @BackupPath + '' + @DBNamewithDateTime + '.bak''
              WITH NOFORMAT, NOINIT,  NAME = N''' + @DBNamewithDateTime 
              + '-Full Database Backup'',
                 SKIP, NOREWIND, NOUNLOAD, COMPRESSION,  STATS = 10'

  PRINT @SQL
  EXEC (@SQL)
  FETCH NEXT FROM Cur INTO @DatabaseName
END
CLOSE Cur
DEALLOCATE Cur


I execute above script on my SQL Server Instance and it took the full backups of databases as shown below with datetime.
How to take full backup of all databases from SQL Server Instance by using TSQL

1 comment:

  1. One thing I’ve learned is to always check for reviews from other players, as their feedback can give you an honest look at what you can expect. I’ve come across https://melbet-app.pro/ which, despite not allowing you to play directly, offers a solid app for tracking games and understanding what works best for your gaming style. It’s always wise to start with platforms that are known for their credibility and customer service. It’s not just about winning but also ensuring you’re playing on a safe and trustworthy site. Take your time and do some research before diving into any game.

    ReplyDelete