1

Consider there are three tables in database, say person, student, teacher.

person (person_id, name, person specific columns...),
student(student_id, foreignKey(person_id), student specific columns... )
teacher(teacher_id, foreignKey(person_id), teacher specific columns... )

using SMO, I am able navigate to person table from both student and teacher table.

   ServerConnection serverConnection = new ServerConnection(conn);
   Server server = new Server(serverConnection);
   Database db = server.Databases[databaseName];
   Table tbl = db.Tables("student");

   foreach (ForeignKey fk in tbl.ForeignKeys)
   { 
       //do something
   }

I want to get the reverse, like what are all the tables (keys) referring Person table's person_id as foreign key, using C# SMO.

P.S: please advice or suggest using C#, but not using DMV. Thanks in Advance

Nageswaran
  • 7,481
  • 14
  • 55
  • 74
  • Looks like this is duplicate of . You don't need SMO for this. You can use `INFORMATION_SCHEMA`. All information on existing objects is stored in tables and all you need is to know how to select it. – T.S. Nov 16 '13 at 18:20

1 Answers1

2

If you really want to use SMO, you can use the DependencyWalker object for this.

Example:

var tbl = db.Tables["person"];
var dw = new DependencyWalker(server);
var tree = dw.DiscoverDependencies(new SqlSmoObject[] {tbl}, DependencyType.Children);
var cur = tree.FirstChild.FirstChild;
while (cur != null)
{
    var table = server.GetSmoObject(cur.Urn) as Table;
    if (table != null && table.ForeignKeys.Cast<ForeignKey>().Any(fk => fk.ReferencedTable == tbl.Name))
    {
        //do something with table.Name
    }
    cur = cur.NextSibling;
}
Joseph Sturtevant
  • 13,194
  • 12
  • 76
  • 90