Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

SQL Server: use parameter in CREATE DATABASE

I want to specify the path where data file and log file is created in a SQL script using parameters. Here is what I wrote:

DECLARE @DataFilePath AS NVARCHAR(MAX)

SET @DataFilePath = N'C:ProgramDataGemcom'

DECLARE @LogFilePath AS NVARCHAR(MAX)

SET @DataFilePath = N'C:ProgramDataGemcom'


USE master
Go
CREATE DATABASE TestDB
ON 
PRIMARY 
( NAME = N'TestDB_Data', FILENAME = @DataFilePath )
LOG ON 
( NAME = N'TestDB_Log', FILENAME = @LogFilePath  )

GO

Unfortunately, this doesn't work. When I try to run it in SQL Server Management Studio, I got the error

Incorrect syntax near '@DataFilePath'.

I am wondering if what I intended to do is even possible?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will have to use dynamic SQL

SELECT @sql = 'CREATE DATABASE TestDB ON PRIMARY ( NAME = ''TestDB_Data'', 
 FILENAME = ' + quotename(@DataFilePath) + ') LOG ON ( NAME = ''TestDB_Log'', 
FILENAME = ' + quotename(@LogFilePath) + ')'

EXEC (@sql)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...