How to create a database in sql server with database name and path as input variables
=>Below stored procedure example illustrates how to create a new database.
=> and adds database name and path as an input variable.
Create proc createTestDatabase(@databasename as varchar(120),@drivename as varchar(500))
as
Begin
Declare @stmt as nvarchar(max);
IF (EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = @databasename))
BEGIN
EXEC('DROP DATABASE ' + @databasename);
END
Set @stmt='
CREATE DATABASE ' + @databasename +
' ON (NAME = N''' + @databasename + '''' +
', filename = N''' + @drivename + '\' + @databasename + '.mdf' + '''' + ', SIZE = 1024MB, FILEGROWTH = 256MB)' +
' LOG ON (NAME = N''' + @databasename + '_log' + '''' +
', FILENAME = N''' + @drivename + '\' + @databasename + '_log.ldf' + '''' + ', SIZE = 512MB, FILEGROWTH = 125MB)'
Select @stmt
Execute (@stmt);
End
How to execute the above stored proc:
Declare @databasename as varchar(150);
Declare @drivepath as varchar(500);
Set @databasename = 'testDatabase11';
Set @drivepath= 'D:\mcj';
Exec createTestDatabase @databasename, @drivepath;