考虑数据库中有三个表,比如人,学生,老师。
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... )
使用SMO,我可以从学生和教师桌面导航到人员表。
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
}
我想要反过来,就像使用C#SMO将Person表的person_id作为外键引用的所有表(键)一样。
P.S:请建议或建议使用C#,但不要使用DMV。 在此先感谢
答案 0 :(得分:2)
如果您真的想使用SMO,可以使用DependencyWalker对象。
示例:强>
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;
}