在SQL Server中无法创建相同的表两次

0 c# sql-server visual-studio-2010

我有一个C#Windows窗体应用程序.我按下一个按钮,它应该创建一个表并插入一个值(int).我将初始数据库创建为服务数据库(添加新项目>数据>服务数据库).

按钮的代码是(输出如下):

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection thisConnection = new SqlConnection(Properties.Settings.Default.Database1ConnectionString);
    SqlCommand nonqueryCommand = thisConnection.CreateCommand();

    try
    {
        thisConnection.Open();

        nonqueryCommand.CommandText = "CREATE TABLE MyTable1 (intColumn int)";
        Console.WriteLine(nonqueryCommand.CommandText);
        Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());

        nonqueryCommand.CommandText = "INSERT INTO MyTable1 VALUES (99)";
        Console.WriteLine(nonqueryCommand.CommandText);
        Console.WriteLine("Number of Rows Affected is: {0}",
           nonqueryCommand.ExecuteNonQuery());
    }
    catch (SqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        thisConnection.Close();  // close connection
        Console.WriteLine("Connection Closed.");
    }
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:CREATE TABLE MyTable1(intColumn int)受影响的行数为:-1 INSERT INTO MyTable1 VALUES(99)受影响的行数为:1连接已关闭.

服务器资源管理器上没有显示任何内容即使我关闭它并重新连接也没有其他表.

如果我按下按钮使其再次发出相同的结果我得到:

System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyTable1' in the database.
Run Code Online (Sandbox Code Playgroud)

但在服务器资源管理器上仍然没有.

Joh*_*ers 5

例外情况告诉你到底发生了什么.你的桌子已经存在.你不能再创建它.如果表已经存在,则需要删除表.