SMO sample code

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

namespace script_data
{
    class Program
    {
        static void Main(string[] args)
        {
            Server srv = new Server("my_server");
            Database db = srv.Databases["my_db"];
            UrnCollection urns = new UrnCollection();

            // tables
            urns.Add(db.Tables["tb1"].Urn);
            urns.Add(db.Tables["tb2"].Urn);
            urns.Add(db.Tables["tb3"].Urn);
            urns.Add(db.Tables["tb4"].Urn);
            urns.Add(db.Tables["tb5"].Urn);

            Scripter scrp = new Scripter(srv);
            scrp.Options.DriAll = true;            
            scrp.Options.IncludeIfNotExists = true;
            scrp.Options.ScriptData = true;
            scrp.Options.ScriptDrops = false;
            scrp.Options.TargetServerVersion = SqlServerVersion.Version90;
            scrp.Options.WithDependencies = true;

            int i = 0;
            foreach (string s in scrp.EnumScript(urns))
            {
                Console.WriteLine(s);
                if (s.StartsWith("INSERT "))
                    if (i == 0)
                        i = 1000;
                    else
                        i--;
                else
                    i = 0;
                    
                if(i == 0)
                    Console.WriteLine("GO");
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s