Getting a string from a variable

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 is this not working?

He gives:

Msg 102, level 15, state 1, line 3 Invalid syntax near '@dbfilepath'.

+3
source share
2 answers

You need to execute 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)
+1
source

Try the following:

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

To use @dbfilepath in a Create Database statement, you must use dynamic sql.

0
source

All Articles