Thursday, June 4, 2009

Generate SQL Index scripts using C#

Problem Statement:

SQL Server 2005 management studio does not provide any method to generate Index scripts all at once. A simple C# program can help in this case:

Sample Console Program:

Make sure following dlls are referenced in your program:













using System;
using System.Collections.Generic;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Text;
using System.Collections.Specialized;

namespace DBScripts
{
class Program
{
static void Main(string[] args)
{
string servername;
string databasename;
servername = "localhost";
databasename = "Northwind";
Server server = new Server(servername);
Database db = server.Databases[databasename];
ScriptingOptions so = new ScriptingOptions();
so.ScriptDrops = false;
so.NonClusteredIndexes = true;
so.IncludeIfNotExists = true;
so.DriForeignKeys = false;
so.FileName = DateTime.Now.ToString().Replace("/"," ").Replace(":"," ") + "indexes.sql";
so.AppendToFile = true;
foreach (Table t in db.Tables)
{
foreach (Index i in t.Indexes)
i.Script(so);
Console.WriteLine(t.Name);
}
}
}
}