Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 13th, 2012  |  syntax: None  |  size: 1.36 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Invoke SQL Script Wizard programmatically
  2. using System;
  3. using Microsoft.SqlServer.Management.Smo;
  4. using Microsoft.SqlServer.Management.Sdk.Sfc;
  5.  
  6.  
  7. public class A {
  8.    public static void Main() {
  9.       String dbName = "AdventureWorksLT2008R2"; // database name
  10.  
  11.       // Connect to the local, default instance of SQL Server.
  12.       Server srv = new Server();
  13.  
  14.       // Reference the database.  
  15.       Database db = srv.Databases[dbName];
  16.  
  17.       // Define a Scripter object and set the required scripting options.
  18.       Scripter scrp = new Scripter(srv);
  19.       scrp.Options.ScriptDrops = false;
  20.       scrp.Options.WithDependencies = true;
  21.       scrp.Options.Indexes = true;   // To include indexes
  22.       scrp.Options.DriAllConstraints = true;   // to include referential constraints in the script
  23.  
  24.       // Iterate through the tables in database and script each one. Display the script.  
  25.       foreach (Table tb in db.Tables) {
  26.          // check if the table is not a system table
  27.          if (tb.IsSystemObject == false) {
  28.             Console.WriteLine("-- Scripting for table " + tb.Name);
  29.  
  30.             // Generating script for table tb
  31.             System.Collections.Specialized.StringCollection sc = scrp.Script(new Urn[]{tb.Urn});
  32.             foreach (string st in sc) {
  33.                Console.WriteLine(st);
  34.             }
  35.             Console.WriteLine("--");
  36.          }
  37.       }
  38.    }