博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

用SMO(sql server management object)生成创建表的脚本

Posted on 2010-05-13 20:10  codingsilence  阅读(393)  评论(0编辑  收藏  举报

如果要生成脚本,需要的引用 为

C:/Program Files (x86)/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.ConnectionInfo.dll

C:/Program Files (x86)/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.Management.Sdk.Sfc.dll

C:/Program Files (x86)/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.Smo.dll

C:/Program Files (x86)/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.SmoExtended.dll

C:/Program Files (x86)/Microsoft SQL Server/100/SDK/Assemblies/Microsoft.SqlServer.SqlEnum.dll

 

下面做一个抛砖引玉,贴一下生成脚本的源码

 

代码
 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Collections.Specialized;

namespace geyunfei
{
    
class Program
    {
        
static void Main(string[] args)
        {

            
//初始化一个连接 
            Server server = new Server(new ServerConnection(
                
"localhost""sa"""));
            
//得到数据库
            var srcDb = server.Databases["TestDB"];
            
//得到表
            Table table = srcDb.Tables["Table1"];

 

          
            
//初始化Scripter 
            Scripter a = new Scripter();
            a.Options.Add(ScriptOption.DriAllConstraints);
            a.Options.Add(ScriptOption.DriAllKeys);
            a.Options.Add(ScriptOption.Default);
            a.Options.Add(ScriptOption.ContinueScriptingOnError);
            a.Options.Add(ScriptOption.ConvertUserDefinedDataTypesToBaseType);
            a.Options.Add(ScriptOption.IncludeIfNotExists);
            


          
            UrnCollection collection 
= new UrnCollection();

            collection.Add(table.Urn);

            var sqls 
=  a.Script(collection);

            
foreach (var s in sqls)
            {
                System.Console.WriteLine(s);
            }

           
        }
    }
}