How can I get a list of the order of tables?
I have two databases (same schema) and I want to import data from the first into the second database.
But now I have a constraint problem. So I have to order the tables before inserting. That's my C# code:
public static void SQLUpdate(DataSet ds)
{
foreach (DataTable table in ds.Tables)
{
string TableName = table.TableName;
DataTable CurrentDt = clsDatabase.SQLQuery("SELECT * FROM " + TableName);
SqlDataAdapter da = new SqlDataAdapter("Select * FROM " + TableName, con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
foreach (DataRow row in table.Rows)
{
DataRow[] drs = CurrentDt.Select(String.Format("[ID] = '{0}'", row["ID"].ToString()));
// No entry? INSERT!
if (drs == null || drs.Length == 0)
{
da.InsertCommand = cb.GetInsertCommand();
da.Update(new DataRow[] { row });
}
// Entry? UPDATE!
else if (drs.Length == 1)
{
da.UpdateCommand = cb.GetUpdateCommand();
da.UpdateCommand.CommandText += " WHERE ID = @ID";
da.Update(drs);
}
}
}
}
For example: two tables:
PERSON: ID, Name, AdressID
ADRESS: ID, Town
Person.ID = 1, Person.Name = "John Doe", Person.AdressID = 1
Adress.ID = 1, Adress.Town = "Downtown"
That's the rows of the first database. I want to import it in the second database with my code.
The address has to be the first insert, cause the foreign key. Then I can import the Person.
And now I need a list of the table order, where I can see that I have to import the Address
before the Person
.