以编程方式调用SQL脚本向导

时间:2011-06-08 05:02:44

标签: sql tsql command-line command-line-arguments wizard

如果有人以编程方式或通过命令行调用SQL脚本向导,有人可以告诉我吗?

这是一个很好的部署工具,但我厌倦了每次使用它时都要设置无数的选项。

2 个答案:

答案 0 :(得分:3)

SSMS脚本向导只是Scripter SMO对象功能的shell。从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("--");
         }
      } 
   }

答案 1 :(得分:0)

您应该在创建和更改表结构时自己编写脚本,它们应该在源代码管理中并与特定版本相关联。处理数据库更改没有任何理由与任何其他代码不同,并且永远不应使用GUI进行数据库更改。