Click here to Skip to main content
15,881,882 members
Articles / Mobile Apps / Windows Mobile

Create a SQL Database Programmatically

Rate me:
Please Sign up or sign in to vote.
3.49/5 (18 votes)
24 Oct 2008CPOL2 min read 104.4K   4.1K   57   12
In this article, I will explain how to use Microsoft SQL Management Objects (SMO) to create a Microsoft SQL database from C# code.
Image 1

Introduction

In this article, I will explain how to use Microsoft SQL Management Objects (SMO) to create a Microsoft SQL database from C# code. In this sample, I will:

  1. Enumerate all the SQL servers in the network and fill a list box where the user can select one of the servers.
  2. The user will enter the Database Name to create.
  3. The user will enter an AD account to grant right to.
  4. When the user clicks "Create Database", the system will check for the existence of the database.

Background

SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server. You can use SMO to build customized SQL Server management applications. Although SQL Server Management Studio is a powerful and extensive application for managing SQL Server, there might be times when you would be better served by an SMO application.

Enumerating SQL Servers

The SmoApplication.EnumAvailableSqlServers() enumerates a list of available instances of Microsoft SQL Server. It returns a DataTable object value that contains an enumerated list of information about the available instances of SQL Server. The table describes the different columns of the returned DataTable.

Column Data type Description
Name String The name of the instance of SQL Server.
Server String The name of the server on which the instance of SQL Server is installed.
Instance String The instance of SQL Server.
IsClustered Boolean A Boolean value that is true if the instance is participating in failover clustering, or false if it is not.
Version String The version of the instance of SQL Server.
IsLocal Boolean A Boolean value that is true if the instance is local, or false if the instance is remote.
C#
DataTable dt = SmoApplication.EnumAvailableSqlServers();
foreach (DataRow dr in dt.Rows)
{ 
this.cbServers.Items.Add(dr[0]);
} 

Connecting to SSQL Server

First we check if the user selected the local server or a SQL server:

C#
//Connect to the local, default instance of SQL Server.
string srvname = this.cbServers.SelectedItem as string;
Server srv;
if (srvname == null)
{
    srv = new Server();
    sb.AppendLine("Connected to local SQL server");
}
else 
{
    srv = new Server(srvname);
    sb.AppendLine(string.Format("Connected to {0}", srvname));
}

Checking If the Database Exists

It is easy to check if the database already exists or not, just use the Databases attribute of the server as follows:

C#
//Define a Database object variable by supplying the server and the 
//database name arguments in the constructor. 
Database db = srv.Databases[this.tbDBName.Text.Trim()];
if (db != null)
{
    if (MessageBox.Show(string.Format
	("The '{0}' already exists do you want to drop it?", this.tbDBName.Text), 
	"Warning", MessageBoxButtons.YesNo, 
	MessageBoxIcon.Question) == DialogResult.Yes)else 
    {
        if (MessageBox.Show(string.Format
	("Create the Tables and Stored Procedures for BT Error Manager on '{0}'?", 
	this.tbDBName.Text), "Warning", MessageBoxButtons.YesNo, 
	MessageBoxIcon.Question) == DialogResult.Yes)
        {
            b.AppendLine("Creating the Tables and Stored Procedures.");
            this.tbProgress.Text = sb.ToString();
            db.ExecuteNonQuery(dbstring);
            sb.AppendLine(string.Format
	   ("Created the Tables and Stored Procedures for BT Error Manager on '{0}'", 
	   this.tbDBName.Text));this.tbProgress.Text = sb.ToString();
	   this.tbProgress.ScrollToCaret();"Proceed or select another database");
	   this.tbProgress.Text = sb.ToString();this.tbProgress.ScrollToCaret();
            return; 

Creating the Database

To create a database, all you have to do is create a new Database object with the Server and the name of the database, then call the Create method.

C#
db = new Database(srv, this.tbDBName.Text);
this.tbProgress.Text = sb.ToString();
this.tbProgress.ScrollToCaret();
//Create the database on the instance of SQL Server. 
db.Create();
sb.AppendLine("Created the database.");
sb.AppendLine("Creating the Tables and Stored Procedures.");
this.tbProgress.Text = sb.ToString();this.tbProgress.ScrollToCaret(); 

Running the SQL Script

The last step is to run the script that will create the tables, views, stored procedures, etc.

C#
//'Reference the database and display the date when it was created. 
db.ExecuteNonQuery(dbstring);

Notes

If you want to use this code in your project, you will need to add references to the SMO assemblies. You can locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Smo.dll
  • Microsoft.SqlServer.SqlEnum.dll
  • Microsoft.SqlServer.SmoEnum.dll
C#
}
sb.AppendLine(
}
}
{
    db.Drop();
}

History

Visit www.MoustafaRefaat.com to find more information.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Canada Canada
As a well-established IT leader with a passion for architecture, design, coding, refactoring, and development, I possess 20+ years’ success spearheading large teams to deliver the end-to-end development of 30+ innovative software solutions on time and under budget on a US and international level.

Throughout my career, I have made it my priority to utilize current technologies and new techniques to develop elegant, creative technical solutions across all project phases. Comfortable in collaborative and independently-driven roles, I am a forward-thinking leader with refined analytical and critical thinking skills, and I can adapt and revise my strategies to meet evolving priorities, shifting needs, and emergent issues. As a dynamic leader with experience as Technical Lead and Senior Manager, as well as on the Board of Directors, I have led numerous teams to create a new employees experience with Workday, roadmap for people systems (JDA WFMR, Kronos, Infor, Workday, and monitoring with Splunk), and architecture for 20+ projects at Loblaw. Furthermore, I have spearheaded As a well-established IT leader with a passion for architecture, design, coding, refactoring, and development, I possess 20+ years’ success spearheading large teams to deliver the end-to-end development of 30+ innovative software solutions on time and under budget on a US and international level.

Throughout my career, I have made it my priority to utilize current technologies and new techniques to develop elegant, creative technical solutions across all project phases. Comfortable in collaborative and independently-driven roles, I am a forward-thinking leader with refined analytical and critical thinking skills, and I can adapt and revise my strategies to meet evolving priorities, shifting needs, and emergent issues. As a dynamic leader with experience as Technical Lead and Senior Manager, as well as on the Board of Directors, I have led numerous teams to create a new employees experience with Workday

Comments and Discussions

 
GeneralMy vote of 4 Pin
Mohammed Hameed31-May-13 3:57
professionalMohammed Hameed31-May-13 3:57 
QuestionMissing an assembly ? Get error message ! Please help. Pin
gautom bose30-Aug-12 14:20
gautom bose30-Aug-12 14:20 
QuestionCreating Database Propgramitically Pin
solomon20110-Mar-12 9:55
solomon20110-Mar-12 9:55 
GeneralCreating database in another place Pin
persiaprog4-Jul-10 6:24
persiaprog4-Jul-10 6:24 
GeneralRun the existing SQL Script programmatically with SMO Pin
elizas25-Mar-10 2:46
elizas25-Mar-10 2:46 
Generalwell..few comments Pin
Md. Marufuzzaman25-Aug-09 6:03
professionalMd. Marufuzzaman25-Aug-09 6:03 
GeneralRe: well..few comments Pin
Md. Marufuzzaman25-Aug-09 6:06
professionalMd. Marufuzzaman25-Aug-09 6:06 
Generalthanks for info Pin
yianfang31-Jan-09 3:56
yianfang31-Jan-09 3:56 
QuestionAnother one? Pin
Not Active22-Feb-08 7:42
mentorNot Active22-Feb-08 7:42 
AnswerRe: Another one? Pin
Moustafa Refaat25-Feb-08 5:47
Moustafa Refaat25-Feb-08 5:47 
GeneralRe: Another one? Pin
Not Active25-Feb-08 6:37
mentorNot Active25-Feb-08 6:37 
JokeRe: Another one? Pin
myklk21-Apr-08 4:18
myklk21-Apr-08 4:18 
I would have to agree with you - except for the fact that this one jumps up to #5 in Google - so there are really only 4 other more relevant search results.

I guess then by your standards, this article was very much needed Smile | :)

It it would seem that both you and I found it and thought it was worthy to comment about. It was brief to the point and got me some cheap code to do what I was looking for - in fact what I googled for.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.