2017-10-20 110 views
1

我需要每天進行數據庫備份並將日期添加到數據庫名稱 - 例如:Navigate_2017-10-20.bak我需要使用數據庫備份數據庫名稱

如何在數據庫名稱和日期中使用動態查詢?

DECLARE @Date DATE = GETDATE() 

SELECT @Date 

BACKUP DATABASE [Navigate] 
TO DISK = N'D:\Working\Navigate_'+ @Date +'.bak' 
WITH NOFORMAT, NOINIT, 
NAME = N'Navigate-Full Database Backup', 
SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10 
GO 
+1

是日期是datetime列,如果是的話,你需要將其轉換成VARCHAR –

回答

2

轉換日期爲字符串,並創建事前的文件名:

DECLARE @Filename NVARCHAR(MAX); 

SELECT @FILENAME = N'D:\Working\Navigate_'+ CONVERT(char(10), GetDate(),126) +'.bak'; 


BACKUP DATABASE [Navigate] 
TO DISK = @FILENAME WITH NOFORMAT, NOINIT, 
NAME = N'Navigate-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10; 
GO 
0
DECLARE @Date DATE = GETDATE() 

SELECT @Date 

BACKUP DATABASE [Navigate] 
TO DISK = N'D:\Working\Navigate_'+ CONVERT(NVARCHAR(20),@Date,105) +'.bak' WITH NOFORMAT, NOINIT, 
NAME = N'Navigate-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10 
GO 
0

使用本

DECLARE @Date NVARCHAR(20) = CONVERT(NVARCHAR(20),GETDATE(),105) 
SELECT @Date 
BACKUP DATABASE [Navigate] 
TO DISK = N'D:\Working\Navigate_'+ @Date +'.bak' WITH NOFORMAT, NOINIT, 
NAME = N'Navigate-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10