1

I am trying to attach a DB and can't figure out the syntax.

DECLARE @path1 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp.mdf';
DECLARE @path2 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp_log.ldf';

/* Attach Database */
CREATE DATABASE ProductDB_Temp ON 
( FILENAME = @path1 ) ,
( FILENAME = @path2 )
FOR ATTACH

Error message:

Incorrect syntax near '@path1'. Expecting ID,Integer,Quoted_Id,string or text_lex

if I construct my script like this:

DECLARE @path1 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp.mdf';
DECLARE @path2 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp_log.ldf';

/* Attach Database */
CREATE DATABASE ProductDB_Temp ON 
( FILENAME = N'D:\MSSQL\DATA\ProductDB_Temp.mdf' ) ,
( FILENAME = N'D:\MSSQL\DATA\ProductDB_Temp_log.ldf' )
FOR ATTACH

it works but this is not really what I would like to do.

I am trying to avoid using EXEC. any suggestions?

1
  • Why are you trying to avoid dynamic sql? This is easily accomplished using dynamic sql. Commented Jul 28, 2016 at 15:36

2 Answers 2

0

I don't think you will be able to create the database this way.

You will need dynamic SQL for that. Take a look at this answer.

Sign up to request clarification or add additional context in comments.

Comments

0

Use dynamic SQL like below..

DECLARE @path1 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp.mdf';
DECLARE @path2 varchar(250)=N'D:\MSSQL\DATA\ProductDB_Temp_log.ldf';

/* Attach Database */


declare @sql nvarchar(max)
SET @Sql = 'CREATE DATABASE newdatabase ON
(filename = ' +@path1+'),
(filename = '+@path2+')
FOR ATTACH'

print @sql

check output ,in this case :

CREATE DATABASE newdatabase ON
(filename = D:\MSSQL\DATA\ProductDB_Temp.mdf),
(filename = D:\MSSQL\DATA\ProductDB_Temp_log.ldf)
FOR ATTACH

finally

EXEC(@SQL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.