Welcome to MSDN Blogs Sign in | Join | Help

SQL Server: SMO Scripting Basics

Let's first clarify what I mean by "scripting". It often happens during talks or when I explain SMO fundamentals that eyes gloss over, shortly after which the "what * do you mean by scripting" question pops up (replace the * with your favorite combination of adjective and noun to indicate bewilderment). For people who, unlike me, do not live their lives in SQL land, "scripting" means typically some kind of language script, like perl, VBScript, or others, that allows you, without the use of a development environment to author and execute code". Not so in this case. If I were to be precise, it means "serialize a SMO or DMO object into Transact-SQL". So now we have this out of the way, let's take a look at SMO Scripting.

 

SMO objects, when either just instantiated and not yet persisted, or just retrieved from the server, carry state. For example a StoredProcedure object has a name, a schema, a text body, and maybe some other optional properties. This state can be serialized into a Transact-SQL script that you may store, modify, or execute. As SQL Server’s primary language is Transact-SQL, it’s obvious that one of the tasks that the SMO object model has to perform very well is scripting. SMO objects can be scripted in 5 different ways:

 

  1. By calling the Script() method on the object.
  2. By instantiating a Scripter object, and pass in a reference of the object(s) to be scripted.
  3. Advanced scripting: generating a script in 3 distinct phases (discovery, list, script)
  4. By using the Transfer object.
  5. Indirectly, by capturing the SQL output of the objects

 

I will discuss 1 and 2 and will dedicate some more posts on the other more advanced topics.

Basic Scripting

Let’s start with scripting an existing object, with no options specified (installing AdventureWorks will help running these samples):

 

Server svr = new Server();

foreach (string s in svr.Databases["AdventureWorks"].StoredProcedures["uspGetEmployeeManagers", "dbo"].Script())
{
      Console.WriteLine(s);
}

If you run this code, the script should be emitted to the console. So far pretty straightforward eh?

Scripting Options

If you want to do more than just scripting the object, there are scripting options that you can pass into the Script() method. There 2 ways to pass in Scripting options. The following 2 samples illustrate the different methods of passing in scripting options.

Server svr = new Server();
StoredProcedure sp = svr.Databases["AdventureWorks"].StoredProcedures["uspGetEmployeeManagers", "dbo"];
 
ScriptingOptions so = new ScriptingOptions();
so.IncludeHeaders = true;
so.SchemaQualify = true;
            
foreach (string s in sp.Script(so))
{
      Console.WriteLine(s);
}

In the next sample, you use the ScriptOption class. This class has various static members that each return an instance of a ScriptionOption class.

Server svr = new Server();
StoredProcedure sp = svr.Databases["AdventureWorks"].StoredProcedures["uspGetEmployeeManagers", "dbo"];
 
foreach (string s in sp.Script(ScriptOption.IncludeHeaders + ScriptOption.SchemaQualify))
{
      Console.WriteLine(s);
}

You can take advantage of the fact that the ScriptOption static members returns a ScriptingOption class (through implict conversion), as you can use it as an alternative to construct a Scriptingoption class:

ScriptingOptions so = ScriptOption.IncludeHeaders;
so.SchemaQualify = true;

Script modified objects

You can modify and script an object, without persisting its state. This sample shows how this can be accomplished:

 

Server svr = new Server();

StoredProcedure sp = svr.Databases["AdventureWorks"].StoredProcedures["uspGetEmployeeManagers", "dbo"];

sp.TextHeader = "-- Scripted at " + DateTime.Now.ToString() + "\n\n" + sp.TextHeader;

foreach (string s in sp.Script())
{
      Console.WriteLine(s);
}

 

Ensure that you either call the Refresh() method on the object once you are done, or persist the object by calling Alter(), as this temporary state may cause problems when this object is referenced again for other purposes.

Script non-existing objects

Alternative, you can instantiate a new object, and emit the script for it, without requiring it to exist on the server. In fact the below script will not even connect to the server; this happens all on your client.

Server svr = new Server();

Database db = new Database(svr, "MyDatabase");

db.DatabaseOptions.AutoClose = true;

foreach (string s in db.Script())
{

      Console.WriteLine(s);
}

Using the Scripter object

If you call the Script() method on an object, what actually happens, is that in the background a Scripter() object is instantiated, which performs the various scripting operations. Whereas each object knows how to emit script, the Scripter object pulls it all together, and does special processing before or while generating the output. Let’s take a look how the Scripter object can be used to accomplish the same task as above (scripting a database).

Server svr = new Server();
 
Database db = new Database(svr, "MyDatabase");
db.DatabaseOptions.AutoClose = true;
 
Scripter scripter = new Scripter();
scripter.Server = svr;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
            
SqlSmoObject[] objs = new SqlSmoObject[1];
objs[0] = db;
 
scripter.Script(objs);
 
foreach (string s in scripter.Script(objs))
{
      Console.WriteLine(s);
}

The above samples I have touched on the basis of the scripting operations. In the next posts I will elaborate and show you more complex and elaborate ways to generate script. We made scripting extremely flexible, and hope that this first post helps you to get started with scripting.

Enjoy!
Published Saturday, May 07, 2005 12:51 PM by mwories
Filed under: ,

Comments

# SMO Scripting Basics

Saturday, May 07, 2005 1:35 PM by Michiel Wories
SMO Scripting Basics

# re: SQL Server: SMO Scripting Basics

Wednesday, November 30, 2005 11:20 PM by Rajani
Hi dude
Thanks for the nice article.it is very informative.
BTW i've one question is it possible to use SMO to replicate "Query Designer" programmatically?
i want to write a query builder for end users and am wondering which objects in SMO i need to use to achieve what i want.
You seem to have good understanding of these things and any help on this one much appreciated.
Thanks

# re: SQL Server: SMO Scripting Basics

Tuesday, February 28, 2006 5:59 PM by Shahzad Choudhry
Great, I've gotten my program to script out DBs, tables, and data.  Now I need to know how to run these scripts on a different server at a different location programatically using SMO.  In SQL-DMO it is simple, using the ExecuteImmediate function of the Server object.  Can't figure out how to do this using SMO.  Appreciate any help.  You can E-mail me at schoudhry@gentax.com.

# SQL Management Objects

Wednesday, March 01, 2006 4:59 PM by mehraNikoo.NET
SMO (SQL Management Objects) in SQL Server 2005 replaces SQL-DMO that was present in the earlier...

# re: SQL Server: SMO Scripting Basics

Sunday, March 05, 2006 7:27 PM by Peter Kellner
I've had a couple problems with SMO and I wonder if anyone else has.  Specifically, when I run through stored procedures (just like your example) it is painfully slow.  Maybe 5 a second.  Another problem is filtering on nonsystem objects with either "SVR.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.View), "IsSystemObject"); or View.isSystemObject.

Both cases crash my app.  Any ideas?

# re: SQL Server: SMO Scripting Basics

Monday, April 24, 2006 2:13 PM by ader
How can I script constraints only? (FK, default, etc) so when I do a large data import on multiple tables, I can drop constraints at the beggining, and re-create them at the end.

Thanks!

# re: SQL Server: SMO Scripting Basics

Tuesday, April 25, 2006 7:09 PM by mwories
I am hiding in shame that I did not see your comments... I should have been notified somehow and that did not happen. If your question is still unanswered, please feel free to drop me an email. My email is Michiel.Wories@(the rest is obvious).

# re: SQL Server: SMO Scripting Basics

Friday, July 21, 2006 6:43 AM by karthik
nice. got me started off reading up on SMO.
Thank you.

# re: SQL Server: SMO Scripting Basics

Tuesday, November 28, 2006 2:01 AM by gnom

# re: SQL Server: SMO Scripting Basics

Friday, December 01, 2006 8:50 PM by Vesa Poikaja rvi

<a href= http://forum.lixium.fr/cgi-bin/index.eur?mitsu > wellbutrin sr </a> [url= http://forum.lixium.fr/cgi-bin/index.eur?mitsu ] wellbutrin medication [/url]

# re: SQL Server: SMO Scripting Basics

Friday, December 08, 2006 10:36 AM by Besid,Besid

Very good project! <a href= www.debtconsolidation.newov.info >debt consolidation</a> <a href= www.badcreditloan.newov.info >bad credit loan</a>

# re: SQL Server: SMO Scripting Basics

Monday, December 11, 2006 11:54 PM by Tonik

Well, your site is very good, good news and design...! ))) Happy Christmas! SmilerMan.

# re: SQL Server: SMO Scripting Basics

Thursday, December 14, 2006 8:23 AM by Ocis,Ocis

Very nice resources!<a href= http://betting.ggfix.com >betting</a> <a href= http://wagering.ggfix.com >wagering</a>

# re: SQL Server: SMO Scripting Basics

Monday, December 18, 2006 12:47 PM by Cathy

I liked this site, it's neat. Good job! Would you please also visit my homepage?

<a href=  ></a> [url=][/url]

# re: SQL Server: SMO Scripting Basics

Friday, January 12, 2007 10:48 PM by videochatbox

Hello people! Nice site! <a href='http://hometown.aol.com/videochatbox'>videochatbox</a>

# re: SQL Server: SMO Scripting Basics

Friday, January 19, 2007 1:40 PM by Hairston

Amazing artwork! This is spectacularly done! Please visit my homepage:

<a href= http://fm7.biz/0l6s >buy valium</a> [url=http://fm7.biz/0l6s]buy valium[/url]

# re: SQL Server: SMO Scripting Basics

Wednesday, January 24, 2007 7:45 PM by Preved

# re: SQL Server: SMO Scripting Basics

Monday, February 05, 2007 4:26 AM by Womens

This is my site:

http://shurl.net/2SU

,This is my site:

http://shurl.net/2SU

# re: SQL Server: SMO Scripting Basics

Friday, February 16, 2007 2:39 PM by nude-cams,nude-cams

Hello! Great site!,Hello! Great site!

# re: SQL Server: SMO Scripting Basics

Friday, February 16, 2007 2:40 PM by nude-cams,nude-cams

Hello! Great site!,Hello! Great site!

# re: SQL Server: SMO Scripting Basics

Saturday, March 24, 2007 1:45 PM by eoxlente

Hello!

Hello and congratulations! Very interesting & professional site!

DS2_sp_1

# re: SQL Server: SMO Scripting Basics

Saturday, March 24, 2007 2:45 PM by grimucdo

Hello!

Thanx thanx thanx for such great job done above your website!

DS2_sp_3

# re: SQL Server: SMO Scripting Basics

Saturday, March 24, 2007 8:05 PM by tovnarcy

Hello!

That's friggin' awesome. Thanks to all those involved

DS2_sp_2

# re: SQL Server: SMO Scripting Basics

Saturday, March 31, 2007 7:35 AM by Britneydqiuo

Very nice! I have some LJ with news, check this out:

<a href= http://iwantubadlyz.livejournal.com >Newest news</a>

<a href= http://annakubat.livejournal.com >Check this out</a>

<a href= http://jackie_simpson.livejournal.com >livejournal</a>

# re: SQL Server: SMO Scripting Basics

Saturday, April 14, 2007 12:41 AM by Hillary

# re: SQL Server: SMO Scripting Basics

Wednesday, April 18, 2007 11:13 PM by healthmlc,healthmlc,healthmlc

The Best Catalog.

<a href=http://healthpiece.info/>Real">http://healthpiece.info/>Real Catalog</a>[url=http://healthpiece.info/]The Real Catalog[/url]

# re: SQL Server: SMO Scripting Basics

Tuesday, May 01, 2007 1:24 AM by dietary

# re: SQL Server: SMO Scripting Basics

Thursday, May 03, 2007 3:12 PM by Celebrex Online

Good Work dude! I will visit your website again.

# re: SQL Server: SMO Scripting Basics

Saturday, May 05, 2007 4:37 AM by Albert Bibingo

Frankly, the way things are right now, I'm not sure I'd want to play myself in my very own movie of the week.

# re: SQL Server: SMO Scripting Basics

Monday, May 07, 2007 5:00 PM by valium Genericp

Good Work dude! I will visit your website again.

# re: SQL Server: SMO Scripting Basics

Thursday, May 10, 2007 9:12 AM by Brytney

# re: SQL Server: SMO Scripting Basics

Thursday, May 10, 2007 9:13 AM by Jak

# re: SQL Server: SMO Scripting Basics

Thursday, May 10, 2007 9:15 AM by Mister

# re: SQL Server: SMO Scripting Basics

Thursday, May 10, 2007 9:16 AM by Victor

# re: SQL Server: SMO Scripting Basics

Thursday, May 17, 2007 6:20 PM by Buy Valium

Very good website you have here, After the visit I put my step in to your guestbook.

http://valium1.blogcu.com/ Buy Valium

# re: SQL Server: SMO Scripting Basics

Saturday, May 19, 2007 1:21 AM by Lesbianq Sexa

What a good site! I think it wasnt easy to post here so much information. Thank you, I will add it to my bookmarks

# re: SQL Server: SMO Scripting Basics

Sunday, May 20, 2007 1:45 AM by Lesbianx Sexe

What a good site! I think it wasnt easy to post here so much information. Thank you, I will add it to my bookmarks

# re: SQL Server: SMO Scripting Basics

Monday, May 21, 2007 3:58 AM by Buy Caverta

I found lots of intresting things here. Please more updates.

# re: SQL Server: SMO Scripting Basics

Monday, May 28, 2007 4:09 PM by Buy Caverta

Thanks for taking the time and effort in creating this content to share your knowledge with all of us.

# re: SQL Server: SMO Scripting Basics

Tuesday, May 29, 2007 12:30 AM by Buy Caverta

Site - very comprehensive and meticulous from all sides, its good! Just excellent website, I sure!

# re: SQL Server: SMO Scripting Basics

Sunday, June 03, 2007 1:50 AM by Lesbianh Sexu

Hey! This is really your Work?! Cool! I never earlier did not see sites like this! Tnx!

# re: SQL Server: SMO Scripting Basics

Monday, June 04, 2007 10:51 PM by Buy Caverta

Site - very comprehensive and meticulous from all sides, its good! Just excellent website, I sure!

# re: SQL Server: SMO Scripting Basics

Tuesday, June 05, 2007 7:13 AM by Buy Caverta

Hi Guys! What Your Site Powered By?

# re: SQL Server: SMO Scripting Basics

Wednesday, June 06, 2007 8:29 PM by Designer Handbagsy

This is really fresh idea of the design of the site! I seldom met such in Internet. Good Work dude!

# re: SQL Server: SMO Scripting Basics

Saturday, June 09, 2007 12:51 PM by Luk

# re: SQL Server: SMO Scripting Basics

Tuesday, June 26, 2007 9:41 AM by Bob

adidas trail running shoes

http://www.volny.cz/adidas/

louis vuitton cherry blossom handbags

http://www.volny.cz/luis2007/

# re: SQL Server: SMO Scripting Basics

Monday, July 02, 2007 7:04 PM by Ron

You have very interesting site!

Respect you!

http://louisellipsehandbag.iespana.es

# re: SQL Server: SMO Scripting Basics

Wednesday, August 01, 2007 12:40 PM by kababdoul

Hi fellows, i'm a newbie on your blog and maybe the first time ever that I participate at an online blog; anyway, there's always a first time...

Your short article on basic scripting is quite nice and straight forward - good job - but there's something i don't get right: lots of questions asked but why so few answers??

Somebody was concerned with slow running scripting and I had the same experience; i just corrupted one of my testing SQL Server 2K databases (not really serious but...) while attaching it to an instance of SQL Server 2K5. I just wanted to recover it (the structure and later its contents) through SMO and noticed that scripting process was unbelievable slow (1h 50mn for about 1400 objects [including system objects]) compared to the way SQL Server 2K does the same job...

Any idea off what is wrong or being misused? Quick response would be very appreciated. Thanx in advance.

Abdoul.

PS: If you'd like I can send u the source code.

# re: SQL Server: SMO Scripting Basics

Thursday, March 06, 2008 5:39 PM by real estate c blog

Welcome to <a href="http://real-estate-cblog.info/172.html ">marblehead real estate</a> <a href="http://real-estate-cblog.info/853.html ">real estate adirondacks</a> <a href="http://real-estate-cblog.info/330.html ">montelongo real estate</a> <a href="http://real-estate-cblog.info/91.html ">loudoun county real estate</a> [URL=http://real-estate-cblog.info/82.html]los altos real estate agents[/URL] [URL=http://real-estate-cblog.info/459.html]newark de homes for sale[/URL] more

# re: SQL Server: SMO Scripting Basics

Saturday, March 08, 2008 8:31 AM by credit cars info

Do you like it? <a href="http://credit-cards-info-info.info/312.html ">credit card holder metal accordian</a> <a href="http://credit-cards-info-info.info/417.html ">citifinancial credit card</a> <a href="http://credit-cards-info-info.info/586.html ">sainsburys credit card lost</a> <a href="http://credit-cards-info-info.info/639.html ">acept credit cardc</a> [URL=http://credit-cards-info-info.info/204.html]fd100 credit card printer[/URL] [URL=http://credit-cards-info-info.info/359.html]credit card charge paid consult[/URL] next

# re: SQL Server: SMO Scripting Basics

Sunday, June 15, 2008 8:51 AM by Iyzreajy

Of course, but what do you think about that?,

Anonymous comments are disabled
 
Page view tracker