Friday, July 30, 2021

How to create a database in sql server with database name and path as input variables

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;





No comments:

Post a Comment

Top 15 SQL interview questions for 2-5 years experienced

  1. What is the difference between UNION and UNION ALL? UNION: To select related information from two tables UNION command is used. It is s...