SQL Server2005探索之—— 利用SQL Server2005提供的namespace 编程

   最近,在探索SQL Server2005的新特性,例如,SSIS,Replication.....,利用SSIS(Microsoft SQL Server Integration Services )将Oracle数据库整体迁移到SQL Server2005中(),Replication 实现了多个数据库服务器之间的数据同步,间接的提高的数据库的性能。相信朋友们一定很熟悉,在这里就不再赘述了。那么,今天和朋友们一起讨论讨论,利用SQL Server2005提供的namespace 编程

    在SQL Server2005 的使用当中,从2000起便提供了Script 支持,即

    
 
   这种脚本支持很方便,但需要你去选择,再去执行,time and time again,so boring.....,想个办法用程序实现。
   在TechNet searcher 一下,找到了Table,Index..... 这些class,ok,接着找到SQLServer2005联机丛书上有相关介绍:
   
Here

The Index object represents a Microsoft SQL Server index.

Namespace: Microsoft.SqlServer.Management.Smo
Assembly: Microsoft.SqlServer.Smo (in microsoft.sqlserver.smo.dll)

  仔细看了看Index的Methods,找到了script()方法,对,就这个方法。Now, coding......
 
 1private void indexScript(string servername,string username,string userpwd,string dbname,string tablename,string )schemaname
 2        {
 3            try
 4            {
 5                Server server = new Server(new ServerConnection(servername,username, userpwd));
 6                DatabaseCollection dbcollection = server.Databases;
 7                Database db = dbcollection[dbname];
 8                TableCollection tabCollection = db.Tables;
 9                Table tab = tabCollection[tablename, schemaname];
10                IndexCollection indexCollection = tab.Indexes;
11
12                for (int h = 0; h < indexCollection.Count; h++)
13                {                                       
14                    StringCollection sc = indexCollection[h].Script();
15                    StringBuilder stringbuilder = new StringBuilder();
16                    for (int i = 0; i < sc.Count; i++)
17                    {
18                        stringbuilder.Append(sc[i].ToString() + " ");
19                    }

20
21                    MessageBox.Show(stringbuilder.ToString());
22                 }

23               catch (Exception ex)
24              {
25                   throw new Exception(ex.Message);
26                 }

27           }
   这样就可以将所有 index的script 显示出来,然后你可以再操纵这些script了,例如导称sql文件再执行。至于其他object都可以使用上面的方法。
   上面这个方法只能用于rebuilder数据库对象,因为script():Generates a Transact-SQL script that can be used to re-create the index.
其他select、alter脚本估计也可以用程序实现,我正在找......,找到了再补充,呵呵。
  
原文地址:https://www.cnblogs.com/tianqing/p/1206477.html