Recently I asked in the Forums for help in creating a new database on a SQL Server from within my application. I thought this would be helpful when I installed a custom app at work, where I don't have access to the server, but have permissions to administer the SQL Server 2008 service.
I received a number of helpful suggestions, but they all boiled down to "you can't do it." I hate being told "No" so I searched some more. MSDN was useless, and Google not much better, but I finally found an answer in the Microsoft Technical Support Knowledge Base.
Just in case someone else is looking for a way to do this simple task, I offer the following simple code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DataTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCreateDatabase_Click(object sender, EventArgs e)
{
String str;
SqlConnection myConn = new SqlConnection
("Server=BAAL\\SQLEXPRESS2;Integrated security=SSPI ;database=master");
str = "CREATE DATABASE MyDatabase";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("Database Created Successfully", "MyApp",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyApp", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
}
}
I apologize for the formatting - Opera is a bit user-hostile in that respect.
Your app must be running under an account that has full privileges on the server for this to work, and you'll need to modify the connection string to match your installation, of course. But this worked perfectly on the first attempt, and I thought it worth sharing.