Is it possible, without writing any SQL or using any 3rd party libraries to create a database schema from several ADO.NET DataTables?
-
Ultimately you will have to execute a CREATE TABLE statement, dont you think? You can create a class that encapsulates the process using metadata from the DataTable, of course.Sean Thoman– Sean Thoman2011-07-11 23:22:55 +00:00Commented Jul 11, 2011 at 23:22
-
I would not like to write any SQL.Daniel A. White– Daniel A. White2011-07-11 23:27:33 +00:00Commented Jul 11, 2011 at 23:27
-
How do you expect any table(s) to be created then? I think essentially your question should be -- "Does the .NET Framework come with any functions that automatically create an sql table from a DataTable?" To which the answer is no, as far as I know.Sean Thoman– Sean Thoman2011-07-11 23:28:19 +00:00Commented Jul 11, 2011 at 23:28
Add a comment
|
3 Answers
Its easy to make a function that writes the SQL for you. However if you don't want to use SQL at all I would think you're out of luck:
private string GetSqlCommand(Dictionary<string, Type> schema, string tableName, bool includeIdentity)
{
string sql = "CREATE TABLE [" + tableName + "] (\n";
if (includeIdentity)
sql += "[ID] int not null Identity(1,1) primary key,\n";
foreach (KeyValuePair<string, Type> info in schema)
{
sql += "[" + info.Key + "] " + SQLGetType(info.Value) + ",\n";
}
sql = sql.TrimEnd(new char[] { ',', '\n' }) + "\n";
return sql + ")";
}
Comments
Here is the code
SqlConnection con = connection string;
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
con.close();
I am giving a predefined table-name abcd.