0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
6EQUJ5HD209458b
  • 271
  • 1
  • 3
  • 12
  • 1
    This "sequence" that you need to take care of here really is a **semantic** thing - **YOU** as the owner of the data know that. I don't see any easy way to find this out. So basically, it's up to **YOU** to write your code in a such a way that the proper sequence is being honored - there's no "setting" or anything in ADO.NET that you can turn on so that ADO.NET would do this for you. – marc_s Nov 26 '11 at 11:25
  • But there are steps you can take to determine what the dependencies are between the tables where foreign keys are defined - to be honest that's probably not the hard bit - the problem is dealing with autogenerated key values – Murph Nov 26 '11 at 12:57

2 Answers2

0

Maybe you should just set your constraints do "deferred", so they will be checked on commit, not on every update?

Piotr Zierhoffer
  • 5,005
  • 1
  • 38
  • 59
0

you can start with this query to identify all the foreign keys you have in the system in order to determine what references what to see what order you need:

http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/

Dave Rael
  • 1,759
  • 2
  • 16
  • 21