现在的位置: 首页 > 综合 > 正文

发现数据库对象的依赖关系

2013年09月23日 ⁄ 综合 ⁄ 共 1892字 ⁄ 字号 评论关闭
文章目录
该篇文章是我于2009年6月10日通过自己编写的工具,批量从位于在博客园的博客站点(http://chenxizhang.cnblogs.com)同步而来。文章中的图片地址仍然是链接到博客园的。特此说明!

陈希章

原文地址:http://www.cnblogs.com/chenxizhang/archive/2009/05/24/1488315.html
原文标题:发现数据库对象的依赖关系
原文发表:2009/5/24 8:50:00

SQL Server Management Studio中有一个很有意思的工具,可以查看某个对象的依赖和被依赖关系。如下图所示

image image

假设,我们自己的程序也要实现这样的功能,那么该怎么做呢?

1. 首先,创建一个项目,添加以下三个引用

image imageimage

2. 用如下代码测试

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SqlServer.Management.Smo;

namespace DiscovDepedency
{
    class Program
    {
        ///

        /// 这个程序演示了如何发现数据库对象的依赖关系
        /// 作者:陈希章
        ///

        ///         static void Main(string[] args)
        {
            Server svr = new Server("localhost");
            Database db = svr.Databases["Northwind"];

            Table tb = db.Tables["Orders"];

            DependencyWalker walker = new DependencyWalker(svr);//这是检测关系的一个工具

            //检测依赖该对象的所有其他对象
            Console.WriteLine("依赖Orders表的所有对象");
            DependencyTree tree = walker.DiscoverDependencies(new[] { tb }, DependencyType.Children);
            foreach (var item in walker.WalkDependencies(tree))
            {
                var xpath = item.Urn.XPathExpression;
                var type = item.Urn.Type;

                Console.WriteLine("/tType:{0},Name:{1}", type, string.Format("{0}.{1}",xpath.GetAttribute("Schema",type),xpath.GetAttribute("Name",type)));
            }

            Console.WriteLine("Orders表所依赖的其他对象");
            DependencyTree tree2 = walker.DiscoverDependencies(new[] { tb }, DependencyType.Parents);
            foreach (var item in walker.WalkDependencies(tree2))
            {
                var xpath = item.Urn.XPathExpression;
                var type = item.Urn.Type;

                Console.WriteLine("/tType:{0},Name:{1}", type, string.Format("{0}.{1}", xpath.GetAttribute("Schema", type), xpath.GetAttribute("Name", type)));
            }

            Console.Read();

        }
    }
}

image

作者:陈希章
出处:http://blog.csdn.net/chen_xizhang
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

抱歉!评论已关闭.