Technical Article

Generate All Table Script By Using SMO C#

,

Editor: This space is for you to describe how to setup or use this (briefly)

// Add SMO DLL from "\Microsoft SQL Server\100\SDK\Assemblies" this Path.

using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Diagnostics;
using Microsoft.SqlServer.Management.Smo.Agent;

namespace SMODmo
{
    class TableScript
    {

        public static ServerConnection conn;
        Server srv;
        Scripter scripter;
        Database db;
        static String databaseName, tableName;

        static void Main(string[] args)
        {
            switch (Convert.ToInt32(Console.ReadLine()))
            {
Console.Write("1: For All Table");
Console.Write("2: For Specific Table");
                case 1:
                    conn = TableScript.srvConn();
                    Console.Write("Enter Database Name: ");
                    databaseName = Console.ReadLine();
                    new TableScript().tableScript(Console.ReadLine());
                    break;
                case 2:
                    conn = TableScript.srvConn();
                    Console.Write("Enter Database Name: ");
                    databaseName = Console.ReadLine();
                    Console.Write("Enter Table Name: ");
                    tableName = Console.ReadLine();
                    new TableScript().SpecificTableScript(databaseName, tableName);
                    break;
            }
            Console.WriteLine("Press Any Key For Exit...");
            Console.ReadKey();

        }
        private static ServerConnection srvConn()
        {
//Initializes a new instance of the ServerConnection class with the specified server instance and logon credentials.
//SERVERNAME = Enter Server IP Of SQL Server.
//LOGIN/PASSWORD = Enter Logon Credentials of Database.
            conn = new ServerConnection(SERVERNAME, LOGIN, PASSWORD);
            return conn;
        }
//This Method Generate  Script Of ALl Table...
        private void tableScript(String _databaseName)
        {
            try
            {
                ScriptingOptions scriptOptions = new ScriptingOptions();
                srv = new Server(conn);
                db = srv.Databases[_databaseName];
                StringBuilder sb = new StringBuilder();
                foreach (Table tbl in db.Tables)
                {
                    if (!tbl.IsSystemObject)
                    {
                        ScriptingOptions options = new ScriptingOptions();
                        options.IncludeIfNotExists = true;
                        options.NoCommandTerminator = false;
                        options.ToFileOnly = true;
                        options.AllowSystemObjects = false;
                        options.Permissions = true;
                        options.DriAllConstraints = true;
                        options.SchemaQualify = true;
                        options.AnsiFile = true;
                        options.SchemaQualifyForeignKeysReferences = true;
                        options.Indexes = true;
                        options.DriIndexes = true;
                        options.DriClustered = true;
                        options.DriNonClustered = true;
                        options.NonClusteredIndexes = true;
                        options.ClusteredIndexes = true;
                        options.FullTextIndexes = true;
                        options.EnforceScriptingOptions = true;
                        options.IncludeHeaders = true;
                        options.SchemaQualify = true;
                        options.NoCollation = true;
                        options.DriAll = true;
                        options.DriAllKeys = true;
                        options.ToFileOnly = true;
                        options.NoExecuteAs = true;
                        options.AppendToFile = false;
                        options.ToFileOnly = false;
                        options.Triggers = true;
                        options.IncludeDatabaseContext = false;
                        options.AnsiPadding = true;
                        options.FullTextStopLists = true;
                        options.ScriptBatchTerminator = true;
                        options.ExtendedProperties = true;
                        options.FullTextCatalogs = true;
                        options.XmlIndexes = true;
                        options.ClusteredIndexes = true;
                        options.Default = true;
                        options.DriAll = true;
                        options.Indexes = true;
                        options.IncludeHeaders = true;
                        options.ExtendedProperties = true;
                        options.WithDependencies = true;


                        StringCollection coll = tbl.Script(options);
                        foreach (string str in coll)
                        {
                            sb.Append(str);
                            sb.Append(Environment.NewLine);
                        }
                    }
                }
                System.IO.StreamWriter fs = System.IO.File.CreateText("D:\\TableScript.SQl");
                fs.Write(sb.ToString());
                fs.Close();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
        }
//This Method Generate  Script Of Specific Table..
        private void SpecificTableScript(String _databaseName, String tableName)
        {
            try
            {
                ScriptingOptions scriptOptions = new ScriptingOptions();
                srv = new Server(conn);
                db = srv.Databases[_databaseName];
                StringBuilder sb = new StringBuilder();
                Table tbl = db.Tables[tableName];
                if (!tbl.IsSystemObject)
                {
                    ScriptingOptions options = new ScriptingOptions();
                    options.IncludeIfNotExists = true;
                    options.NoCommandTerminator = false;
                    options.ToFileOnly = true;
                    options.AllowSystemObjects = false;
                    options.Permissions = true;
                    options.DriAllConstraints = true;
                    options.SchemaQualify = true;
                    options.AnsiFile = true;
                    options.SchemaQualifyForeignKeysReferences = true;
                    options.Indexes = true;
                    options.DriIndexes = true;
                    options.DriClustered = true;
                    options.DriNonClustered = true;
                    options.NonClusteredIndexes = true;
                    options.ClusteredIndexes = true;
                    options.FullTextIndexes = true;
                    options.EnforceScriptingOptions = true;
                    options.IncludeHeaders = true;
                    options.SchemaQualify = true;
                    options.NoCollation = true;
                    options.DriAll = true;
                    options.DriAllKeys = true;
                    options.ToFileOnly = true;
                    options.NoExecuteAs = true;
                    options.AppendToFile = false;
                    options.ToFileOnly = false;
                    options.Triggers = true;
                    options.IncludeDatabaseContext = false;
                    options.AnsiPadding = true;
                    options.FullTextStopLists = true;
                    options.ScriptBatchTerminator = true;
                    options.ExtendedProperties = true;
                    options.FullTextCatalogs = true;
                    options.XmlIndexes = true;
                    options.ClusteredIndexes = true;
                    options.Default = true;
                    options.DriAll = true;
                    options.Indexes = true;
                    options.IncludeHeaders = true;
                    options.ExtendedProperties = true;
                    options.WithDependencies = true;


                    StringCollection coll = tbl.Script(options);
                    foreach (string str in coll)
                    {
                        sb.Append(str);
                        sb.Append(Environment.NewLine);
                    }
                }

                System.IO.StreamWriter fs = System.IO.File.CreateText("D:\\SpecificTableScript.SQl");
                fs.Write(sb.ToString());
                fs.Close();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
        }
    }
}

Rate

2.75 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

2.75 (4)

You rated this post out of 5. Change rating