Add date to SQL database backup filename

前端 未结 7 658
旧时难觅i
旧时难觅i 2021-02-01 14:03

I\'m using the below to backup a db from a SQL job. Can someone tell me how to add the current date to the output filename? Preferably in YYYYMMDD format.

BACK         


        
7条回答
  •  轮回少年
    2021-02-01 14:15

    If you want to include the date and time, so you can use:

    DECLARE @MyFileName varchar(200)
    SELECT @MyFileName='\\ServerToSave\Path\MyDB_' + REPLACE(convert(nvarchar(20),GetDate(),120),':','-') + '.bak'
    BACKUP DATABASE [myDB] TO DISK=@MyFileName ...
    

    The 120 in the Convert gives you the yyyy-mm-dd hh:mi:ss(24h)

    The REPLACE function is necessary because the filename can not have the : character.

提交回复
热议问题