Error when restoring database from disk using a variable I have the following query in SQL Server 2014. The backup of the database completes in approx 150 seconds but the restore/verify step fails with an error.

Can you tell me where I'm going wrong? 

I don't understand why I can save the backup using a variable, but I'm unable to restore using the same variable.

Msg 137, Level 15, State 2, Line 36
Must declare the scalar variable "@BackupPath".
Msg 319, Level 15, State 1, Line 36
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.


Line 36 is the RESTORE VERIFYONLY line.

DECLARE @BackupPath varchar(1000)
SELECT @BackupPath = (SELECT N'F:\Backups\DBNAME_' + REPLACE(convert(nvarchar(20),GetDate(),120),':','-') + '.bak')
PRINT @BackupPath

BACKUP DATABASE [DBNAME] TO  DISK = @BackupPath WITH COMPRESSION, NOFORMAT, NOINIT, NAME = N'DBNAME-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
DECLARE @backupSetId as int
SELECT @backupSetId = position from msdb..backupset where database_name=N'Partner' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'DBNAME' )
IF @backupSetId is null
BEGIN
       RAISERROR(N'Verify failed. Backup information for database ''Partner'' not found.', 16, 1)
END
RESTORE VERIFYONLY FROM  DISK = @BackupPath WITH  FILE = @backupSetId,  NOUNLOAD,  NOREWIND
GO
Try removing the 'GO' statement.

Referencing the documentation for SQL Server Utilities Statements - GO


  The scope of local (user-defined) variables is limited to a batch, and
  cannot be referenced after a GO command.