...好友
Os:win2k3
DB:sql server 2008
我打算将最新的备份集从生产恢复到测试数据库。我必须从restore headeronly命令获取最大位置到变量并将其传递给restore命令。
我写了这个查询..但我仍然面临执行此查询的一些问题。
declare @position1 as int
declare @tempsql1 nvarchar(max)
set @tempsql1='RESTORE HEADERONLY FROM DISK = ''D:\DailyDBbackup\ciet.BAK''';
execute(@tempsql1); ======== upto this statement working fine...
SELECT @position1 = MAX(position) FROM @tempsql1 WHERE BackupType = 1 AND BackupName = 'ciet-Full Database Backup';
此处@tempsql1
未从上述变量中获取值。我收到错误
必须声明表变量“@ tempsql1”
RESTORE DATABASE ciet FROM DISK = 'D:\DailyDBbackup\ciet.BAK'
WITH FILE = @position1;
任何人都可以更正此错误吗?
谢谢&问候
我尝试过以下查询...但是再次恢复旧的备份集而不是最大的备份集。
DECLARE @position1 int;
DECLARE @BackupHeader TABLE (
BackupName nvarchar(128)
,BackupDescription nvarchar(255)
,BackupType smallint
,ExpirationDate datetime
,Compressed tinyint
,Position smallint
,DeviceType tinyint
,UserName nvarchar(128)
,ServerName nvarchar(128)
,DatabaseName nvarchar(128)
,DatabaseVersion int
,DatabaseCreationDate datetime
,BackupSize numeric(20,0)
,FirstLSN numeric(25,0)
,LastLSN numeric(25,0)
,CheckpointLSN numeric(25,0)
,DatabaseBackupLSN numeric(25,0)
,BackupStartDate datetime
,BackupFinishDate datetime
,SortOrder smallint
,CodePage smallint
,UnicodeLocaleId int
,UnicodeComparisonStyle int
,CompatibilityLevel tinyint
,SoftwareVendorId int
,SoftwareVersionMajor int
,SoftwareVersionMinor int
,SoftwareVersionBuild int
,MachineName nvarchar(128)
,Flags int
,BindingID uniqueidentifier
,RecoveryForkID uniqueidentifier
--following columns introduced in SQL 2008
,Collation nvarchar(128)
,FamilyGUID uniqueidentifier
,HasBulkLoggedData bit
,IsSnapshot bit
,IsReadOnly bit
,IsSingleUser bit
,HasBackupChecksums bit
,IsDamaged bit
,BeginsLogChain bit
,HasIncompleteMetaData bit
,IsForceOffline bit
,IsCopyOnly bit
,FirstRecoveryForkID uniqueidentifier
,ForkPointLSN numeric(25,0)
,RecoveryModel nvarchar(60)
,DifferentialBaseLSN numeric(25,0)
,DifferentialBaseGUID uniqueidentifier
,BackupTypeDescription nvarchar(60)
,BackupSetGUID uniqueidentifier NULL
,CompressedBackupSize bigint
--following column introduced in SQL 2012
--,Containment tinyint
)
INSERT INTO @BackupHeader
EXEC ('RESTORE HEADERONLY FROM DISK=''D:\DailyDBbackup\121213\ciet.BAK''');
--print @BackupHeader; ==== it shows error so i commented
SELECT @position1 = MAX(position)
FROM @BackupHeader
WHERE
BackupType = 1
AND BackupName = 'ciet-Full Database Backup';
print @position1; ==== here it shows the first position that is 1...max position is 18
IF @position1 IS NULL
BEGIN
RAISERROR('Backup not found', 16, 0);
END
ELSE
BEGIN
RESTORE DATABASE ciet FROM DISK = 'D:\DailyDBbackup\121213\ciet.BAK'
WITH FILE = @position1;
END;
答案 0 :(得分:0)
错误信息足够清楚 - 您不能以这种方式使用@ tempsql1,不是表变量。
没有简单的方法,将选择SQL 添加到变量,然后添加到来自子句。
如果您参与动态SQL生成 - 请阅读此简短指南