I’m connecting to an SQL Server 2008 database.
Using C#, I’d like to create a new table, with a name specified by me, which looks exactly like an existing table in that database. There are no foreign keys involved.
I have code like
DataTable table = con.GetSchema("Tables");
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
But it doesn’t get me very far. Do I really need to iterate over all the tables myself? Even if I identify the DataTable how do I clone it? I looked at DataTable.Clone but I can’t see how to set a new name and create that table on the database.
SMO (Server Management Objects) has a great deal of table scripting abilities. I would start there.
This article might help get you started.
If you want to avoid SMO, you can do it via a SQLDataReader, as follows (or something close to this):