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
>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), ' ', '-'), ':', '-');