0

当谈到确保备份到位的任务时,我有点担心,因为我们使用的是 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

我看到了这个链接:关键字'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".

这个错误让我回到了我最初的想法,即问题在于声明我的变量..

4

1 回答 1

2

BACKUP LOG ...语句之后,您有一个GO关键字。这向 SQL 发出“批处理结束”信号。这也意味着,在 a 之前声明的任何变量GO都不能在 a 之后使用GO

如果您删除GO脚本中的关键字(在BACKUP LOG ...declare @backupSetId as int行之间),您的脚本应该可以工作。

报告的错误“靠近关键字'with'”很可能是指您@filename在该RESTORE VERIFYONLY行中使用的,(显然)靠近另一个关键字'with'。

于 2013-04-26T12:56:42.403 回答