//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 01908433-d6b4-4413-939a-d55d1e4ee364", 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
//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 '01908433-d6b4-4413-939a-d55d1e4ee364' already exists do you want to drop it?", this.tbDBName.Text), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)else
{
db.Drop();
}
{
if (MessageBox.Show(string.Format("Create the Tables and Stored Procedures for BT Error Manager on '01908433-d6b4-4413-939a-d55d1e4ee364'?", this.tbDBName.Text), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
sb.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 '01908433-d6b4-4413-939a-d55d1e4ee364'", 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;
}
sb.AppendLine(
}
}
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.
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.
//'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