[c#] C# - Create SQL Server table programmatically

I am trying to create a SQL Server table programmatically. Here is the code.

using (SqlConnection con = new SqlConnection(conStr))
{

    try
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code uses an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
            command.ExecuteNonQuery();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

When I'm running this application second time I'm getting an exception:

"There is already an object named 'Customer' in the database"

but when I check database I don't see such a table.
Here is my connection string.

<connectionStrings>
  <add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>
</connectionStrings>

When I am running select query; I am getting results from existing tables so I think connection string should be OK. Hope you'll see the problem :/

This question is related to c# .net sql-server create-table

The answer is


You haven't mentioned the Initial catalog name in the connection string. Give your database name as Initial Catalog name.

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects


If you don't like remembering SQL syntax, using Mig# you can simply:

var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
schema.Alter(db => db.CreateTable("Customer")
     .WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
     .WithNotNullableColumn("First_Name", DbType.String).OfSize(50)
     .WithNotNullableColumn("Last_Name", DbType.String).OfSize(50)
     ...);

If you are not sure if it already exists, call DropIfExists before:

db.Tables["Customers"].DropIfExists();

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommend
{
    class sqlcreateapp
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Table Created Successfully...");
                conn.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
            }
            Console.ReadKey();
        }
    }
}

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

First, check whether the table exists or not. Accordingly, create table if doesn't exist.

var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";

using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();

Try this

Check if table have there , and drop the table , then create

using (SqlCommand command = new SqlCommand("IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#Customer%')
DROP TABLE #Customer CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to create-table

Field 'id' doesn't have a default value? MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB Create hive table using "as select" or "like" and also specify delimiter #1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version C# - Create SQL Server table programmatically How do I create a table based on another table Creating new table with SELECT INTO in SQL create table in postgreSQL PostgreSQL Error: Relation already exists Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table