代码之家  ›  专栏  ›  技术社区  ›  David

从中生成SQL Server表架构的代码ADO.NET

  •  0
  • David  · 技术社区  · 14 年前

    我很想用ADO.NET生成创建表脚本以创建给定表的精确副本。

    1 回复  |  直到 14 年前
        1
  •  3
  •   D'Arcy Rittich    14 年前

    SQL Management Objects (SMO)为了这个。

    示例(C#)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using Microsoft.SqlServer.Management.Smo;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Server srv = new Server(@".\SQLEXPRESS");
                Database db = srv.Databases["MyDB"];
    
                Scripter scrp = new Scripter(srv);
                scrp.Options.ScriptDrops = false;
                scrp.Options.WithDependencies = true;
    
                //Iterate through the tables in database and script each one. Display the script. 
                //Note that the StringCollection type needs the System.Collections.Specialized namespace to be included. 
                Microsoft.SqlServer.Management.Sdk.Sfc.Urn[] smoObjects = new Microsoft.SqlServer.Management.Sdk.Sfc.Urn[1];
                foreach (Table tb in db.Tables)
                {
                    smoObjects[0] = tb.Urn;
                    if (tb.IsSystemObject == false)
                    {
                        System.Collections.Specialized.StringCollection sc;
                        sc = scrp.Script(smoObjects);
                        foreach (string st in sc)
                            Console.WriteLine(st);
                    }
                }
                Console.ReadKey();
            }
        }
    }