Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing the Date Format on an SQL Server backup

I have an SQL script that I’m trying to create that will backup an SQL Server database and add a date/time stamp into the backup name.

When I run my script it adds the date in the wrong format and I’m not sure how to rectify it. The date it adds says "01 Sept 2023 09:00:00" when I want to add it like "01-09-2023-09:00:00"

DECLARE @filename varchar(500)
DECLARE @db1 varchar(500)
DECLARE @url varchar(500)
DECLARE @date nvarchar(256)

SET @date = REPLACE(CONVERT(nvarchar(256),GetDate(), 113),':','-');

SELECT @url = 'https://storageaccountname.blob.core.windows.net/sql-migration-data/db1/'
SELECT @date
SELECT @db1 = 'db1_diff_'

SET @filename = @url + @db1 + @date + '.bak'

BACKUP DATABASE [db1] TO  URL = @filename WITH  DIFFERENTIAL , NOFORMAT, NOINIT,  NAME = N'db1-Differential Database Backup', NOSKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want to create an SQL Server backup script that adds a date and time stamp to the backup file name in the format "dd-mm-yyyy-hh:mi:ss". Your current script is producing a different date format. To achieve your desired format, you can use the CONVERT function with style 120 to format the date correctly, and then replace spaces and colons with hyphens in the resulting string.

SET @date = REPLACE(REPLACE(CONVERT(nvarchar(256), GetDate(), 120), ' ', '-'), ':', '-');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading