"使用变量名称创建数据库" -SQL失败

时间:2015-03-16 08:58:23

标签: sql-server

我使用现有数据库通过MS SQL Server Management Tool生成" CREATE" -Script。然后我用变量替换了DB Name的字符串文字。但是,当我执行脚本时,它会在@ DBFullName"附近继续说"错误的语法。 (首次使用' NAME = @DBFullName ...')。我不知道问题是什么,除了可能性,这里禁止使用变量。

DECLARE @DBNAME nvarchar(MAX);
SET @DBNAME = 'MyDataBase'

DECLARE @DBFullName text;
SET @DBFullName = 'MySuperDataBase';

DECLARE @DBFileName text;
SET @DBFileName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\\' + @DBName + '.mdf';
DECLARE @DBLogName text;
SET @DBLogName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\\' + @DBName + '.ldf';

CREATE DATABASE [@DBNAME] ON  PRIMARY 
( NAME = @DBFullName + '_Data', FILENAME = @DBFileName , SIZE = 30720KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
 LOG ON 
( NAME = @DBFullName + '_Log', FILENAME = @DBLogName , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
GO

1 个答案:

答案 0 :(得分:1)

您必须使用动态SQL。此外,您需要将text替换为nvarchar(max),否则文字连接将无效。

这是完整的脚本:

DECLARE @DBNAME nvarchar(MAX);
SET @DBNAME = 'MyDataBase'

DECLARE @DBFullName nvarchar(max);
SET @DBFullName = 'MySuperDataBase';

DECLARE @DBFileName nvarchar(max);
SET @DBFileName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\' + @DBName + '.mdf';
DECLARE @DBLogName nvarchar(max);
SET @DBLogName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\' + @DBName + '.ldf';

DECLARE @SQL nvarchar(max);
SET @SQL = N'CREATE DATABASE [' + @DBNAME + '] ON PRIMARY (NAME = ' + @DBFullName + '_Data, FILENAME = ''' + @DBFileName+ ''' , SIZE = 30720KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%) LOG ON ( NAME = ' + @DBFullName + '_Log, FILENAME = ''' + @DBLogName + ''', SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)'

PRINT @SQL

EXEC (@SQL)
GO

在我的机器上工作! :)