3
DECLARE @dbfilepath nvarchar(128)
SET @dbfilepath = 'C:\SqlDataFiles\Cache.mdf'
GO

USE [master]
GO
CREATE DATABASE [Cache] ON  PRIMARY 
( NAME = N'Cache', FILENAME = @dbfilepath, SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
GO

Why doesn't this work?

It gives:

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '@dbfilepath'.

1
  • You cannot use a variable inside a CREATE DATABASE statement Commented Jun 14, 2011 at 15:48

2 Answers 2

1

You need to exec it;

USE [master]
GO
DECLARE @dbfilepath nvarchar(128) = 'C:\MSSQL\Cache.mdf'
DECLARE @SQL NVARCHAR(MAX) = N'CREATE DATABASE [Cache] ON PRIMARY (NAME = N''Cache'', FILENAME = ''' + @dbfilepath + ''', SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )'
EXEC(@SQL)
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

DECLARE @dbfilepath nvarchar(128);
SET @dbfilepath = 'C:\\SqlDataFiles\\Cache.mdf';
PRINT @dbfilepath;

To use @dbfilepath in the Create Database statement, dynamic sql needs to be used.

2 Comments

It is printing the same path as mentioned.
@SQL. Yes. But now the error won't come, which was mentioned in the question.

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.