ALTER DATABASE / ADD FILE / VARIABLE TO FILINAM?

I want to add a group of files / files to an existing database, but I need to get the path from the variable, because it will be different when this script completes. When I check the script in SQL Management Studio 2008 R2, it returns an error in FILENAME = @Path.

How can i use this variable?

SCRIPT WILL NOT WORK FROM A TEAM LINE!

ALTER DATABASE [MyDB]
ADD FILEGROUP [MyDB_FileStream] CONTAINS FILESTREAM
GO

DECLARE @Path VARCHAR(MAX)
SET @Path = 'C:\whatEverIWantItToBe\ThisCouldChangeWithLogic\YouGetThePoint\'

ALTER DATABASE [MyDB]
ADD FILE
  (NAME = 'MyDB_FileStream'
   , FILENAME = @Path
   )
TO FILEGROUP [MyDB_FileStream]
+5
source share
3 answers

Using dynamic SQL:

Declare @Path nvarchar(max)
Declare @Sql nvarchar(max)

Set @Path = 'C:\whatEverIWantItToBe\ThisCouldChangeWithLogic\YouGetThePoint\'

Set @Sql = 'Alter Database [MyDb]
    Add File( Name = ''MyDb_FileStream''
            , FileName = ' + QuoteName( @Path, '''' ) 
            + ') To FileGroup [MyDbFileStream]'

Exec( @Sql )
+9
source

Not sure if this will work for you, but if you are going to run the script from the command line you can do:

ALTER DATABASE [MyDB]
ADD FILE (NAME = 'MyDB_FileStream', FILENAME = $(path))
TO FILEGROUP [MyDB_FileStream]

And run it with

sqlcmd -s servername -i script.sql -v path="path to the file"
+2

I have not tried, but usually dynamic sql can help solve this problem

0
source

All Articles