脚本错误:SQLCMD:关键字'with'附近的语法不正确

时间:2013-04-26 12:03:52

标签: sql-server database-backups sqlcmd

在确保备份到位的任务时,我有点担心,因为我们正在使用SQL Express,并发现如果不涉及一些脚本,确实没有办法管理它。我对脚本编写很好,但我对SQL语法有点不了解......这是我的脚本。

declare @currentDate datetime
set @currentDate = GetDate() 
declare @fileName varchar(255)

set @fileName = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\AlphaDB_PRD_Trans_'    
+ cast(Year(@currentDate) as varchar(4))
+ Replicate('0', 2 - Len(cast(Month(@currentDate) as varchar(2))))
    + cast(Month(@currentDate) as varchar(2))
+ Replicate('0', 2 - Len(cast(Day(@currentDate) as varchar(2))))
    + cast(Day(@currentDate) as varchar(2))
+ '_' +    
+ Replicate('0', 2 - Len(cast(DatePart(hour, @currentDate) as varchar(2))))
    + cast(DatePart(hour, @currentDate) as varchar(2))    
+ Replicate('0', 2 - Len(cast(DatePart(minute, @currentDate) as varchar(2))))
    + cast(DatePart(minute, @currentDate) as varchar(2)) + '.TRN';

BACKUP LOG [AlphaDB_PRD] TO DISK = @fileName with DESCRIPTION = N'AlphaDB_PRD-Transaction Log  Backup', NOFORMAT, INIT,  NAME = N'AlphaDB_PRD-Transaction Log  Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
declare @backupSetId as int
select @backupSetId = position from msdb..backupset where database_name=N'AlphaDB_PRD' and   backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'AlphaDB_PRD' )
if @backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''AlphaDB_PRD'' not found.', 16, 1) end
RESTORE VERIFYONLY FROM DISK = @fileName WITH FILE = @backupSetId,  NOUNLOAD,  NOREWIND
GO

我认为我最初的问题是我为filename声明变量的方式 但实际文件已保存:AlphaDB_PRD_Trans_20130426_0738.TRN

我看到了这个链接:Incorrect syntax near the keyword 'with'. 但是当我在关键字;之前加入WITH时,我收到了另一个错误:

Msg 102, Level 15, State 1, Server ALPHASRVPRD, Line 17
Incorrect syntax near '='.
Msg 137, Level 15, State 2, Server ALPHASRVPRD, Line 4
Must declare the scalar variable "@fileName".

并且该错误让我回到我最初的想法,即问题是声明我的变量..

1 个答案:

答案 0 :(得分:2)

BACKUP LOG ...语句后,您有GO个关键字。这表示“批处理结束”为SQL。这也意味着,GO之前声明的任何变量都不能在GO之后再次使用。

如果您删除了脚本中的GO关键字(BACKUP LOG ...declare @backupSetId as int行之间),那么您的脚本应该有效。

报告的错误“near keyword'with'”最有可能是指您在@filename行使用RESTORE VERIFYONLY,(显然)在另一个关键字'附近'。