动态传递Create Database脚本的位置和文件名

时间:2013-07-30 15:19:36

标签: sql sql-server sql-server-2008 tsql

我正在尝试将新文件组和文件添加到现有数据库中。

我的剧本:

DECLARE @AlterDB NVarchar(4000),
        @FGName NVarchar(30) = 'Partition_DW2_',
        @FileLoc NVarchar(50) ='D:\Data\',
        @CurrentYR NVarchar(10) ='2014' ,
        @FullName Nvarchar(max) 
 Set @FullName = @FileLoc+@FGName+@CurrentYR+'.ndf'
        Print @fullName
et @AlterDB = 'ALTER DATABASE Partition_DWJ2
                        ADD FILE 
                        (   NAME =  '+@FGName+@CurrentYR+',FILENAME ='+@FullName +',SIZE = 2048KB ,MAXSIZE = UNLIMITED,FILEGROWTH = 1024KB
                        )TO FILEGROUP '+@FGName+@CurrentYR

            EXECUTE SP_Executesql @AlterDB ,N'@FullName NVarchar(max)',@FullName=@FullName
            Print @ALterDB 

这会产生错误'Incorrect syntax near 'D:'.'

我做错了什么?

2 个答案:

答案 0 :(得分:4)

好吧,假设您在脚本上实际使用Set @AlterDB而不是et @AlterDB,则需要将文件名括在单引号上:

DECLARE @AlterDB NVarchar(4000),
        @FGName NVarchar(30) = 'Partition_DW2_',
        @FileLoc NVarchar(50) ='D:\Data\',
        @CurrentYR NVarchar(10) ='2014' ,
        @FullName Nvarchar(max) 
 Set @FullName = @FileLoc+@FGName+@CurrentYR+'.ndf'
        Print @fullName
 Set @AlterDB = 'ALTER DATABASE Partition_DWJ2
                        ADD FILE 
                        (   NAME =  '+@FGName+@CurrentYR+',FILENAME ='+CHAR(39)+@FullName+CHAR(39)+',SIZE = 2048KB ,MAXSIZE = UNLIMITED,FILEGROWTH = 1024KB
                        )TO FILEGROUP '+@FGName+@CurrentYR

            EXECUTE SP_Executesql @AlterDB ,N'@FullName NVarchar(max)',@FullName=@FullName
            Print @ALterDB 

答案 1 :(得分:0)

尝试在@FileLoc NVarchar(50) = 'D:\\Data\\'

中添加另一个反斜杠