WordsOnTech

Taking SQL Server Backups in yyyymmdd_hhmmss format

When we configure native log shipping, it takes log backups in yyyymmdd_hhmmss format. Recently, we had requirement where customer wanted us to take other native backups in yyyymmdd_hhmmss format. We used below code for taking different backups in required format.

Full Backup

DECLARE @FullFileName varchar(1000)

-- Full backup File Name in yyyymmdd_hhmmss format

SELECT @FullFileName = (SELECT 'D:\Backup\Test_Full_' + convert(varchar(30),getDate(),112)+  '_'+
       replace(convert(varchar(30), getdate(),108),':','')  + '.bak')

--print @FullFileName

-- Run Full backup
Backup Database Test
to disk = @FullFileName

Differential Backup

DECLARE @DiffFileName varchar(1000)

-- Differential backup File Name in yyyymmdd_hhmmss format

SELECT @DiffFileName = (SELECT 'D:\Backup\Test_Diff_' + convert(varchar(30),getDate(),112)+  '_'+
       replace(convert(varchar(30), getdate(),108),':','')  + '.bak')

--print @DiffFileName

-- Run Differential backup 
Backup Database Test
to disk = @DiffFileName
with Differential

Log backup

DECLARE @LogFileName varchar(1000)

-- Log backup File Name in yyyymmdd_hhmmss format

SELECT @LogFileName = (SELECT 'D:\Backup\Test_Log_' + convert(varchar(30),getDate(),112)+  '_'+
       replace(convert(varchar(30), getdate(),108),':','')  + '.bak')

--print @LogFileName

-- Run Log backup 
Backup Log Test
to disk = @LogFileName
Exit mobile version