Last active
February 2, 2024 22:12
-
-
Save petesql/9c3f79039e36f801911819c8a572a346 to your computer and use it in GitHub Desktop.
Generate SQL for a Database Full Backup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Generate SQL for running a full database backup | |
DECLARE @DatabaseName NVARCHAR(255) = 'Jupiter'; -- Replace with your actual database name | |
DECLARE @BackupDirectory NVARCHAR(255) = 'D:\mssql_backups'; -- Replace with your desired backup directory | |
DECLARE @Compression BIT = 1; -- 1 for compression, 0 for no compression | |
DECLARE @NumberOfFiles INT = 1; -- Specify the desired number of backup files | |
DECLARE @BackupDate SMALLDATETIME = CONVERT(SMALLDATETIME, GETDATE(), 101); -- Get current date with MM/DD/YYYY format | |
DECLARE @FormattedBackupDate NVARCHAR(20) = REPLACE(REPLACE(CONVERT(NVARCHAR(20), @BackupDate, 106), ' ', '_'), ',', ''); | |
DECLARE @BackupFiles TABLE (FileIndex INT, FileName NVARCHAR(255)); | |
-- Generate backup file names | |
INSERT INTO @BackupFiles | |
SELECT FileIndex, @DatabaseName + '_Full_' + @FormattedBackupDate + '_Part' + CAST(FileIndex AS NVARCHAR(5)) + '.bak' | |
FROM (SELECT TOP (@NumberOfFiles) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS FileIndex FROM master.dbo.spt_values) AS Numbers | |
ORDER BY FileIndex; | |
-- Generate backup SQL script | |
DECLARE @SQLScript NVARCHAR(MAX); | |
SET @SQLScript = | |
'BACKUP DATABASE [' + @DatabaseName + '] ' + | |
'TO ' + | |
(SELECT STRING_AGG('DISK = N''' + @BackupDirectory + '\' + FileName + '''', ', ') WITHIN GROUP (ORDER BY FileIndex) FROM @BackupFiles) + | |
' WITH ' + | |
'COMPRESSION, ' + | |
'STATS = 10'; | |
-- Output the generated SQL script to a grid in SSMS | |
SELECT [GeneratedSQLScript] = @SQLScript; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment