使用动态SQL进行数据库备份

时间:2017-07-07 16:44:57

标签: sql sql-server dynamic-sql

我正在创建一个工作,它将备份数据库并使用今天的文件名后缀日期。但是我得到了以下错误。

DECLARE @Query NVARCHAR(MAX)
SET @Query = 'BACKUP DATABASE [DBName] TO DISK = ''D:\Backups\DBName_'+cast(convert(date,getdate())as varchar)+'.bak'
EXEC sp_executeSql @Query

错误消息:

Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string 'D:\Backups\DBName_2017-07-07.bak'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'D:\Backups\DBName_2017-07-07.bak'.

2 个答案:

答案 0 :(得分:1)

您错过了最后一个收盘报价。它应以.txt'''

结尾
SET @Query = 'BACKUP DATABASE [MetaCost] TO DISK = ''D:\Backups\DBName.bak_'+cast(convert(date,getdate())as varchar)+'.txt'''

通常也使用.bak扩展名进行sql数据库备份。

答案 1 :(得分:0)

您的陈述将输出

BACKUP DATABASE [DBName] TO DISK =' D:\ Backups \ DBName.bak_2017-07-07.txt

您需要添加#assume this is the date as NOW() SET @mycurrentDate = '2017-06-21T12:00:00'; SELECT * FROM product WHERE product_id IN ( SELECT product_id FROM ( SELECT id, @mycurrentDate AS `current_date`, `tn`.`start` AS `starts_on`, `tn`.`end` AS `ends_on`, `tn`.`product_id` AS `Product_id`, IF(`tn`.`end` >= @mycurrentDate, DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends 0 #the event has already passed ) AS `days_remaining` FROM `booking` AS `tn` ) tmp1 WHERE `days_remaining` = 0 )