There is a saying : “Better safe then sorry” well I’ve learned this the hard way a couple of times ;)…
Nowadays when I’m at a customer’s site and I have to change or do something regarding their MS SQL databases I always ask for a backup first. But sometimes the MS SQL server is a MS SQL Express or the customer doesn’t have the proper backup mechanism in place to backup the databases. Then this script comes in handy!
First you run the following query in the MS SQL Server Management Studio to create a stored procedure in MS SQL .
MSSQL Express Backup Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
USE [master] GO /****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[sp_BackupDatabases] @databaseName sysname = null, @backupType CHAR(1), @backupLocation nvarchar(200) AS SET NOCOUNT ON; DECLARE @DBs TABLE ( ID int IDENTITY PRIMARY KEY, DBNAME nvarchar(500) ) -- Pick out only databases which are online in case ALL databases are chosen to be backed up -- If specific database is chosen to be backed up only pick that out from @DBs INSERT INTO @DBs (DBNAME) SELECT Name FROM master.sys.databases WHERE state=0 AND name=@DatabaseName OR @DatabaseName IS NULL ORDER BY Name -- Filter out databases which do not need to backed up IF @backupType='F' BEGIN DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks') END ELSE IF @backupType='D' BEGIN DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks') END ELSE IF @backupType='L' BEGIN DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks') END ELSE BEGIN RETURN END -- Declare variables DECLARE @BackupName varchar(100) DECLARE @BackupFile varchar(100) DECLARE @DBNAME varchar(300) DECLARE @sqlCommand NVARCHAR(1000) DECLARE @dateTime NVARCHAR(20) DECLARE @Loop int -- Loop through the databases one by one SELECT @Loop = min(ID) FROM @DBs WHILE @Loop IS NOT NULL BEGIN -- Database Names have to be in [dbname] format since some have - or _ in their name SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']' -- Set the current date and time n yyyyhhmmss format SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','') -- Create backup filename in path\filename.extension format for full,diff and log backups IF @backupType = 'F' SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK' ELSE IF @backupType = 'D' SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK' ELSE IF @backupType = 'L' SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN' -- Provide the backup a name for storing in the media IF @backupType = 'F' SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime IF @backupType = 'D' SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime IF @backupType = 'L' SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime -- Generate the dynamic SQL command to be executed IF @backupType = 'F' BEGIN SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' END IF @backupType = 'D' BEGIN SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' END IF @backupType = 'L' BEGIN SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' END -- Execute the generated SQL command EXEC(@sqlCommand) -- Goto the next database SELECT @Loop = min(ID) FROM @DBs where ID>@Loop END |
After this you can open a command prompt (or create a batch file) and use one the following lines depending on the MS SQL authentication to run the MS SQL backup :
1 |
sqlcmd -U <strong>SQLLogin</strong> -P <strong>Password</strong> -S .\<strong>SQLEXPRESS</strong> -Q "EXEC sp_BackupDatabases @backupLocation ='<strong>D:\SQLBackups</strong>', @BackupType=’<strong>F</strong>’" |
Windows Authentication
1 |
sqlcmd -S .\<strong>SQLEXPRESS</strong> -E -Q "EXEC sp_BackupDatabases @backupLocation='<strong>D:\SQLBackup\</strong>', @backupType='<strong>F</strong>'" |
Remember to change the bold variables to your own needs and voila you’re “safe”!
Possible “Backuptypes” :
F = Full
D = Differential
L = Log
It is also possible to create a scheduled task which runs a batch file containing the following lines which automatically cleans up old database backup files after the backup :
1 2 |
sqlcmd -S .\<strong>SQLEXPRESS</strong> -E -Q "EXEC sp_BackupDatabases @backupLocation='<strong>D:\SQLBackup\</strong>', @backupType='<strong>F</strong>'" sqlcmd -S .\<strong>SQLEXPRESS</strong> -E -Q "DECLARE @Retention VARCHAR(50) Set @Retention=CAST(DATEADD(d, -<strong>5</strong>, GETDATE()) AS VARCHAR) EXEC master.dbo.xp_delete_file 0,N'<strong>D:\SQLBackup\</strong>',N'bak',@Retention" |
Note : The backup retention in the script above is set to 5 days please change to your own requirement!