Home

ADO.NET - How To: Create a Table

     

Introduction

This is an example of creating a table in a Microsoft SQL Server database.

private void btnDatabase_Click(object sender, EventArgs e)
{
    using (SqlConnection connection =
	new SqlConnection("Data Source=(local);" +
			  "Database='Exercise1';" +
			  "Integrated Security=yes;"))
    {
	SqlCommand command =
		 new SqlCommand("CREATE TABLE Customers (" +
				"DrvLicNbr NVarChar(50), " +
				"DateIssued Date," +
				"DateExpired Date," +
				"FullName nvarchar(120)," +
				"Address NVARCHAR(120)," +
				"City nvarchar(50)," +
				"State nvarchar(100)," +
				"PostalCode nvarchar(20)," +
				"HomePhone nvarchar(20)," +
				"OrganDonor bit);",
				connection);
	connection.Open();
	command.ExecuteNonQuery();

	MessageBox.Show("A new table named \"Customers\" has been created.");
    }
}

Here is an example of creating a table that has an identity column:

private void btnDatabase_Click(object sender, EventArgs e)
{
    using (SqlConnection connection =
	new SqlConnection("Data Source=(local);" +
			  "Database='Exercise1';" +
			  "Integrated Security=yes;"))
    {
	SqlCommand command =
	    new SqlCommand("CREATE TABLE StoreItems( " +
		 	   "StoreItemID int IDENTITY(1, 1) NOT NULL, " +
			   "Category varchar(50), " +
			   "[Item Name] varchar(100) NOT NULL, " +
			   "Size varchar(20), " +
			   "[Unit Price] money);",
			   connection);
	connection.Open();
	command.ExecuteNonQuery();

	MessageBox.Show("A new table named StoreItems has been crated.");
    }
}
 
 

Home Copyright © 2011 C#Key