Creating a database programmatically in SQL Server

You can either use the SQL Server Management Object API (see task “creating, altering and removing databases“):

 var srv = new Server();
 var db = new Database(srv, "mydb");
 db.Create();

Information on how to get started is here. During SQL server installation you need to install the client SDK, the SMO assemblies are in C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies

Or if you don’t want the dependency on these assemblies, you can also simply run DDL statements using ADO.Net (e.g. see this question):

using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "CREATE DATABASE mydb";
    command.ExecuteNonQuery();
}  

Obviously you need a correct connection string: known sql server instance and a user with CREATE DATABASE permission.

Leave a Comment