Invoke SQL Script Wizard programmatically

半腔热情 提交于 2019-12-13 03:57:32

问题


Could someone please tell me if there is someway to invoke the SQL Script Wizard programmatically or through the command line?

It's a great tool for deployment but I am sick of having to set the countless options each time I use it.


回答1:


The SSMS scripting wizard is just a shell over the Scripter SMO object capabilities. From the scripting example on MSDN:

using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Sdk.Sfc;


public class A {
   public static void Main() { 
      String dbName = "AdventureWorksLT2008R2"; // database name

      // Connect to the local, default instance of SQL Server. 
      Server srv = new Server();

      // Reference the database.  
      Database db = srv.Databases[dbName];

      // Define a Scripter object and set the required scripting options. 
      Scripter scrp = new Scripter(srv);
      scrp.Options.ScriptDrops = false;
      scrp.Options.WithDependencies = true;
      scrp.Options.Indexes = true;   // To include indexes
      scrp.Options.DriAllConstraints = true;   // to include referential constraints in the script

      // Iterate through the tables in database and script each one. Display the script.   
      foreach (Table tb in db.Tables) { 
         // check if the table is not a system table
         if (tb.IsSystemObject == false) {
            Console.WriteLine("-- Scripting for table " + tb.Name);

            // Generating script for table tb
            System.Collections.Specialized.StringCollection sc = scrp.Script(new Urn[]{tb.Urn});
            foreach (string st in sc) {
               Console.WriteLine(st);
            }
            Console.WriteLine("--");
         }
      } 
   }



回答2:


You should be writing the scripts yourself as you create and change table structures, they should be in source control and associated with a particular release. There is no excuse for treating database changes any different than any other code and database changes should never be made using the GUI.



来源:https://stackoverflow.com/questions/6274401/invoke-sql-script-wizard-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!