简体   繁体   中英

Get list of referencing tables in SQL Server using C#, SMO

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.

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM