我编写了以下过程来创建一系列20个数据库。 但它并没有创造它们。即使我去H:驱动器并且没有找到名为bharath1 bharath2的ldf和mdf,就不会创建数据库......
我做错了什么?
USE master
GO
DECLARE @command varchar(1000), @i int
while @i < 5
SET @command = 'CREATE DATABASE Bharath' + CAST(@i AS varchar) + '
ON ( NAME = ''Bharath_dat'',
FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\Bharath' +
CAST(@i AS varchar) + '.mdf'', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 )
LOG ON ( NAME = ''Bharath_log'',
FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\Bharath' +
CAST(@i AS varchar) + '.ldf'', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB )'
EXEC (@command)
SET @i = @i + 1
GO
据我所知,我对SQL Server存储过程没有任何想法,并且有人支持我这样做。但我找不到任何数据库。
非常感谢任何帮助。
答案 0 :(得分:4)
好的,我没有在WHILE循环之后看到BEGIN和END块,这可能导致SQL执行无限循环来仅运行SET @command语句。
您需要将WHILE与BEGIN和END ...
括起来DECLARE @command as varchar(1000), @i int
SET @i = 0
WHILE @i < 5
BEGIN
SET @command = 'CREATE DATABASE Example' + CAST(@i AS varchar)
EXEC(@command)
SET @i = @i + 1
END
这对我有用。 (SET @ i = 0必须)
答案 1 :(得分:2)
你需要初始化@i,在声明后添加:
SET @i = 1
答案 2 :(得分:2)
你错过了一些事情 - 你首先需要将你想要反复执行的几个SQL命令放到BEGIN......END
块中。
其次,您需要初始化@i
计数器!否则,它首先从不进入WHILE循环。
第三,你的CREATE DATABASE调用是错误的 - 你需要指定一个文件组在哪里创建数据库(CREATE DATABASE(name)ON(filegroup).......)。
这是我的代码:
USE master
GO
DECLARE @command varchar(1000), @instanceName VARCHAR(100), @i int
SET @i = 1
WHILE @i <= 5
BEGIN
SET @instanceName = 'Bharath' + CAST(@i AS VARCHAR(10))
SET @command = 'CREATE DATABASE ' + @instanceName +
' ON PRIMARY ( NAME = N''' + @instanceName + ''', ' +
'FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\' +
@instanceName + '.mdf'', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) ' +
'LOG ON ( NAME = N''' + @instanceName + '_LOG'', ' +
'FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\' +
@instanceName + '.ldf'', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB )'
EXEC (@command)
SET @i = @i + 1
END
GO