SQL服务器,如何使用字符串变量?

时间:2014-02-19 16:34:54

标签: sql-server

在SQL server中,如何使用字符串变量?例如,我想编写一个脚本来自动执行数据库恢复,但它会在'+'附近抱怨语法错误。

如何解决?

declare @source varchar(20) = 'Adventureworks2012';
declare @destination varchar(20) = 'Adventureworks2012_copy';

RESTORE DATABASE @source
FROM DISK = @destination
WITH REPLACE, 
MOVE @source+'_Data' TO 'C:\test\Adventureworks2012_20140301_Data.mdf'

1 个答案:

答案 0 :(得分:1)

尝试以下内容:

DECLARE @Source varchar(50) = 'Adventureworks2012';
DECLARE @Destination varchar(50) = 'Adventureworks2012_copy';
DECLARE @SourceDB varchar(500)
DECLARE @DestinationDB varchar(500)


SET @SourceDB = @Source + '_Data'
SET @DestinationDB = 'C:\test\Adventureworks2012_20140301_Data.mdf'

RESTORE DATABASE @Source
FROM DISK = @Destination
WITH REPLACE, 
MOVE @SourceDB TO @DestinationDB