Script index definition

The SMO library is used by SSMS to generate table/index definition. 

Need to add reference to the below dll files. The example scripts the index definition for a given table.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.SqlServer.Management.Smo;

using Microsoft.SqlServer.Management.Sdk.Sfc;  

//add refrence

// /r:Microsoft.SqlServer.Smo.dll

// /r:Microsoft.SqlServer.ConnectionInfo.dll

// /r:Microsoft.SqlServer.SqlEnum.dll

// /r:Microsoft.SqlServer.Management.Sdk.Sfc.dll

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            String server_name = "aubriprbiw09";          

            String database_name = "EDW_700_Presentation_Layer";

            String table_name = "dim_Customer_Table";

            StringBuilder sb = new StringBuilder();

            Server srv;

            srv = new Server(server_name);

            Database db;

            db = srv.Databases[database_name];

            ScriptingOptions so = new ScriptingOptions();

            so.IncludeIfNotExists = true;

            so.ClusteredIndexes = true;

            so.NonClusteredIndexes = true;

            so.Indexes = true;

            so.FullTextIndexes = true;

   

            foreach (Table tb in db.Tables) 

            {

                if (tb.Name == table_name && tb.IsSystemObject == false)

                {

                    foreach (Index i in tb.Indexes)

                    {

                        System.Collections.Specialized.StringCollection sc = i.Script(so);

                        foreach (string st in sc)

                        {

                            sb.AppendLine(st);

                        }

                    }

                }

            }

            Console.WriteLine(sb.ToString());

    

            Console.Read();

            srv.ConnectionContext.Disconnect();

        }

    }

}