Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a database programmatically in SQL Server

How can I create a database programmatically and what is the minimum information I need to do this?

Please no "SQL Server Management Object API " suggestions.

like image 471
Pascal Avatar asked Jan 26 '12 07:01

Pascal


People also ask

How do I create a SQL Server database?

Use SQL Server Management StudioRight-click Databases, and then select New Database. In New Database, enter a database name. To create the database by accepting all default values, select OK; otherwise, continue with the following optional steps. To change the owner name, select (...) to select another owner.

Can you use JavaScript in SQL?

SQL. js is a JavaScript library that allows you to create and query a relational database entirely in the browser. It uses a virtual database file stored in the browser memory, so it doesn't persist the changes made to the database. This library also uses Emscripten to compile SQLite to WebAssembly (Wasm).

What does Msdb do in SQL Server?

The msdb database is used by SQL Server Agent for scheduling alerts and jobs and by other features such as SQL Server Management Studio, Service Broker and Database Mail. For example, SQL Server automatically maintains a complete online backup-and-restore history within tables in msdb.


2 Answers

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.

like image 146
jeroenh Avatar answered Oct 04 '22 01:10

jeroenh


Create database 'Databasename'
like image 26
Glenn Avatar answered Oct 04 '22 00:10

Glenn