user595234
user595234

Reputation: 6259

SQL server, how to use a string variable?

In the SQL server, how to use a string variable ? for example, I want to write a script to automate database restore, but it complains syntax error near '+' .

how to fix it ?

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'

Upvotes: 0

Views: 58

Answers (1)

Shiva
Shiva

Reputation: 20955

Try something like the following:

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

Upvotes: 1

Related Questions