如何使用SQL存储过程创建数据库?为什么我不能将数据库作为变量发送?
从外部发送数据库名称是否有限制?如果有这样的限制,我怎么能这样做?
create proc AddDatabase
@Name varchar(100),
@FileName varchar(Max),
@Size int,
@Maxsize int,
@FileGrowth int,
@logName varchar(100),
@LogFileName varchar(Max),
@LogSize int,
@LogMaxsize int,
@LogFileGrowth int)
as
begin
Create database @Name
On Primary
(NAME=@Name
FileName=@FileName,
Size=@size
MaxSize=@Maxsize,
FileGrowth=@FileGrowth
)
log on
(NAME=@logName,
FILENAME=@LogFileName,
SIZE=@LogSize,
MAXSIZE=@LogMaxsize,
FILEGROWTH=@LogFileGrowth
)
end
答案 0 :(得分:1)
其他人是对的,您需要使用动态SQL。这应该可以让你得到你想要的东西,但请注意我没有测试过。
CREATE PROC AddDatabase @Name varchar(100),
@FileName varchar(MAX),
@Size int,
@MaxSize int,
@FileGrowth int,
@LogName varchar(100),
@LogFileName varchar(MAX),
@LogSize int,
@LogMaxsize int,
@LogFileGrowth int
AS
DECLARE @SQL nvarchar(MAX), @Params nvarchar(MAX);
SET @SQL = N'
CREATE DATABASE ' + QUOTENAME(@Name) + N' ON PRIMARY
(NAME = @dName,
FILENAME = @dFileName,
SIZE = @dSize,
MAXSIZE = @dMaxSize,
FILEGROWTH = @dFileGrowth)
LOG ON (NAME = @dLogName,
FILENAME = @dLogFileName,
SIZE = @dLogSize,
MAXSIZE = @dLogMaxsize,
FILEGROWTH = @dLogFileGrowth);';
SET @Params = N'@dName varchar(100), @dFileName varchar(MAX), @dSize int, @dMaxSize int, @dFileGrowth int, @dLogName varchar(100), @dLogFileName varchar(MAX), @dLogSize int, @dLogMaxsize int, @dLogFileGrowth int';
EXEC sp_executesql @SQL, @Params, @dName = @Name, @dFileName = @FileName, @dSize = @Size, @dMaxSize = @MaxSize, @dFileGrowth = @FileGrowth, @dLogName = @LogName, @dLogFileName = @LogFileName, @dLogSize = @LogSize, @dLogMaxsize = @LogMaxsize, @dLogFileGrowth = @LogFileGrowth;
GO