Add date to SQL database backup filename

前端 未结 7 570
旧时难觅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:29

    Maybe you want to use windows task, just put the code in a bat file and add to your Windows tasks:

    for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
    set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
    set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
    
    set "fullstamp=%YYYY%%MM%%DD%-%HH%%Min%%Sec%"
    set bkfile=dbname%fullstamp%.bak
    set path_sqlcmd="C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\SQLCMD.exe"
    
    %path_sqlcmd% -S .\SQLEXPRESS -E -Q "BACKUP DATABASE seteo TO DISK='D:\bk-sqlserver\%bkfile%' WITH FORMAT"
    

    It's a bit long, but i think it's a practical solution, if you need backup sql server 2005 or oldie versions, just change sqlcmd by osql.

提交回复
热议问题