ALTER DATABASE / ADD FILE / VARIABLE FILENAME?

时间:2011-04-08 04:29:20

标签: sql tsql sql-server-2008

我想将文件/文件组添加到现有数据库,但我需要从变量中获取路径,因为在完成此脚本时它将有所不同。当我在SQL Management Studio 2008 R2中检查脚本时,它会在FILENAME = @Path返回错误。

我该如何使用该变量?

SCRIPT将不会从命令行开始运行!

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]

3 个答案:

答案 0 :(得分:9)

使用动态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 )

答案 1 :(得分:2)

不确定这是否适合您,但如果您要从命令行运行脚本,则可以执行以下操作:

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

运行它:

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

答案 2 :(得分:0)

我没试过,但通常动态的sql可以帮助解决这类问题