SQL Server 2008 - 使用命令行创建数据库脚本(模式+数据)

app*_*orm 9 sql-server sql-server-2008 database-schema

在SSMS中,当我单击数据库"Tasks - > Generate Scripts"时,我得到一个输出脚本.

如何使用非图形工具执行相同操作?

Rem*_*anu 7

图形工具只是实际实现脚本的SMO类的包装器,如Scripter类.有一个使用MSDN中的SMO 编写数据库中所有表的脚本示例:脚本:

//Connect to the local, default instance of SQL Server. 
{ 
   Server srv = default(Server); 
   srv = new Server(); 
   //Reference the AdventureWorks database. 
   Database db = default(Database); 
   db = srv.Databases("AdventureWorks"); 
   //Define a Scripter object and set the required scripting options. 
   Scripter scrp = default(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. 
   Table tb = default(Table); 
   Urn[] smoObjects = new Urn[2]; 
   foreach ( tb in db.Tables) { 
      smoObjects = new Urn[1]; 
      smoObjects(0) = tb.Urn; 
      if (tb.IsSystemObject == false) { 
         StringCollection sc = default(StringCollection); 
         sc = scrp.Script(smoObjects); 
         string st = null; 
         foreach ( st in sc) { 
            Console.WriteLine(st); 
         } 
      } 
   } 
} 
Run Code Online (Sandbox Code Playgroud)

还有更多示例如何在其他各种网站上使用它.