Creating a SQL Server table from a C# datatable

Viewed 98948

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 columns and data in the DataTable?

9 Answers

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();
Related