Creating a SQL Server table from a C# datatable

前端 未结 9 1074
死守一世寂寞
死守一世寂寞 2020-12-01 01:38

I have a DataTable that I manually created and loaded with data using C#.

What would be the most efficient way to create a table in SQL Server 2005 that uses the col

9条回答
  •  [愿得一人]
    2020-12-01 01:49

    Here is some code that I have written to do just this thing for work in progres sql.

    int count = dataTable1.Columns.Count - 1;
    for (int i = 0; i < dataTable1.Columns.Count; i++)
    {
       if (i == count)
       {
           name += dataTable1.Columns[i].Caption + " VARCHAR(50)";
       }
       else
       {
           name += dataTable1.Columns[i].Caption + " VARCHAR(50)" + ", ";
       }
    }
    
    // Your SQL Command to create a table
    string createString = "CREATE TABLE " + tableName + " (" + name + ")";                     
    //SqlCommand create = new SqlCommand(createString, connection);
    NpgsqlCommand create = new NpgsqlCommand(createString, connection);
    connection.Open();
    create.ExecuteNonQuery();
    

提交回复
热议问题