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
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.
You can use any of them. These Are Sample For Use Date And DateTime In Backup Database:
SELECT 'TestDb' + '_'+CAST(CAST(GETDATE() AS datetime2) AS NVARCHAR(22))+
'_Log.trn';--TestDb_2019-09-28 13:54:42.54_Log.trn
SELECT 'TestDb' + '_'+CAST(CAST(GETDATE() AS DATE) AS NVARCHAR(MAX))+
'_Log.trn';--TestDb_2019-09-28_Log.trn
SELECT 'TestDb' + '_'+CAST(sysdatetime() as nvarchar(max))+ '_Log.trn';--TestDb_2019-09-28 13:54:42.5536994_Log.trn
SELECT 'TestDb'+'_' + convert(varchar(500),GETDATE(),120) + '_Log.trn';--TestDb_2019-09-28 13:54:42_Log.trn
SELECT 'TestDb'+'_' + convert(varchar(500),GETDATE(),112) + '_Log.trn';--TestDb_20190928_Log.trn
SELECT 'TestDb' + '_'+CAST(FORMAT(getdate(), N'yyyy-MM-ddThh:mm:ss') as nvarchar(max))+ '_Log.trn';--TestDb_2019-09-28T02:08:38_Log.trn
DECLARE @MyFileName varchar(1000)
SELECT @MyFileName = (SELECT '\\ServerToSave\Path\MyDB_' + convert(varchar(500),GetDate(),112) + '.bak')
BACKUP DATABASE [myDB] TO DISK=@MyFileName ...
DECLARE @var nvarchar(max) ='C:\Projects\myDatabase ' +replace(rtrim(convert(char,getdate())), ':',',')+'.bak';
BACKUP DATABASE myDatabase TO DISK = @var
output:
C:\Projects\myDatabase Jun 3 2015 6,33AM.bak
Try this.
DECLARE @MyFileName varchar(50)
SELECT '\\ServerToSave\Path\MyDB_' + convert(nvarchar(20),GetDate(),112) + '.bak'
BACKUP DATABASE [myDB] TO DISK=@MyFileName ...
The 112 in the Convert gives you the YYYYMMDD format
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.