简体   繁体   中英

Append Date to Filename in Windows Batch File

I have a batch file which backs up my SQL Database and want to append the date to the end of the file created.

sqlcmd -U sa -P pwd -S SERVER\\SQL2012 -Q "BACKUP DATABASE [MYDB] TO DISK = N'E:\\Databases\\MYDB.bak' WITH NOFORMAT, NOINIT, NAME = N'MYDB-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10" -d "MYDB"

Currently all my back ups are getting added to the MYDB.bak file but I want to have new file names for each backup with the date eg MYDB20141028.bak

You can get the current date by parsing the output of the date command.

The following will work if your locale is US English.

for /f "tokens=2,3,4 delims=/ " %%i in ('date /t') do set DATE=%%k%%i%%j

It will take the output of date /t and re-arrange it. The delimiters are set to be the forward slash and space. Then it takes tokens 2,3,4 and outputs them in the order 4,2,3.

So it will take Mon 10/27/2014 and split it into the tokens:

  1. Mon
  2. 10
  3. 27
  4. 2014

And will set the DATE variable to 20141027 .

With that you can change our backup command to:

sqlcmd -U sa -P pwd -S SERVER\SQL2012 -Q "BACKUP DATABASE [MYDB] TO DISK = 
N'E:\Databases\MYDB%DATE%.bak' WITH NOFORMAT, NOINIT, NAME = N'MYDB-Full Database Backup', SKIP,
NOREWIND, NOUNLOAD, STATS = 10" -d "MYDB"

An option if you want to do the date appending in SQL is to pass multiple commands like this:

sqlcmd -U sa -P pwd -S SERVER\\SQL2012 -Q "DECLARE @dest NVARCHAR(max);SET @dest = N'E:\\Databases\\MYDB' + CONVERT(varchar(8),GETDATE(), 112) + '.bak';BACKUP DATABASE [MYDB] TO DISK = @dest' WITH NOFORMAT, NOINIT, NAME = N'MYDB-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10" -d "MYDB"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM