SQL Server: SMO Scripting Basics

Published 07 May 05 12:51 PM | mwories 

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!
Filed under: ,

Comments

# Michiel Wories said on May 7, 2005 1:35 PM:
SMO Scripting Basics
# Rajani said on November 30, 2005 11:20 PM:
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
# Shahzad Choudhry said on February 28, 2006 5:59 PM:
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.
# mehraNikoo.NET said on March 1, 2006 4:59 PM:
SMO (SQL Management Objects) in SQL Server 2005 replaces SQL-DMO that was present in the earlier...
# Peter Kellner said on March 5, 2006 7:27 PM:
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?
# ader said on April 24, 2006 2:13 PM:
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!
# mwories said on April 25, 2006 7:09 PM:
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).
# karthik said on July 21, 2006 6:43 AM:
nice. got me started off reading up on SMO.
Thank you.
# gnom said on November 28, 2006 2:01 AM:

<a href=http://akoc-icco.ru/wholesale-nursery>wholesale nursery</a>

# Vesa Poikaja rvi said on December 1, 2006 8:50 PM:

<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]

# Besid,Besid said on December 8, 2006 10:36 AM:

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

# Tonik said on December 11, 2006 11:54 PM:

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

# Ocis,Ocis said on December 14, 2006 8:23 AM:

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

# Cathy said on December 18, 2006 12:47 PM:

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

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

# videochatbox said on January 12, 2007 10:48 PM:

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

# Hairston said on January 19, 2007 1:40 PM:

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]

# Preved said on January 24, 2007 7:45 PM:

Thank you!

http://symy.jp/?Ct_220745,Thank">http://symy.jp/?Ct_220745,Thank you!

http://symy.jp/?Ct_220745

# Womens said on February 5, 2007 4:26 AM:

This is my site:

http://shurl.net/2SU

,This is my site:

http://shurl.net/2SU

# nude-cams,nude-cams said on February 16, 2007 2:39 PM:

Hello! Great site!,Hello! Great site!

# nude-cams,nude-cams said on February 16, 2007 2:40 PM:

Hello! Great site!,Hello! Great site!

# eoxlente said on March 24, 2007 1:45 PM:

Hello!

Hello and congratulations! Very interesting & professional site!

DS2_sp_1

# grimucdo said on March 24, 2007 2:45 PM:

Hello!

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

DS2_sp_3

# tovnarcy said on March 24, 2007 8:05 PM:

Hello!

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

DS2_sp_2

# Britneydqiuo said on March 31, 2007 7:35 AM:

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>

# Hillary said on April 14, 2007 12:41 AM:

Hello, nice site look this:

http://jewl.info/salt-crystal-lamp-in-usa

http://jewl.info/salt-crystal-lamp-in-usa

http://jewl.info/salt-crystal-lamp-in-usa

AST_spmt3

# healthmlc,healthmlc,healthmlc said on April 18, 2007 11:13 PM:

The Best Catalog.

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

# dietary said on May 1, 2007 1:24 AM:

<a href= http://dietary-supplements.piercing-shop.biz >dietary</a>

# Celebrex Online said on May 3, 2007 3:12 PM:

Good Work dude! I will visit your website again.

# Albert Bibingo said on May 5, 2007 4:37 AM:

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.

# valium Genericp said on May 7, 2007 5:00 PM:

Good Work dude! I will visit your website again.

# Brytney said on May 10, 2007 9:12 AM:

good news

http://wapurl.co.uk/?ITYQ7HN

# Jak said on May 10, 2007 9:13 AM:

good news

http://wapurl.co.uk/?ITYQ7HN

# Mister said on May 10, 2007 9:15 AM:

good news

http://wapurl.co.uk/?ITYQ7HN

# Victor said on May 10, 2007 9:16 AM:

good news

http://wapurl.co.uk/?ITYQ7HN

# Buy Valium said on May 17, 2007 6:20 PM:

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

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

# Lesbianq Sexa said on May 19, 2007 1:21 AM:

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

# Lesbianx Sexe said on May 20, 2007 1:45 AM:

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

# Buy Caverta said on May 21, 2007 3:58 AM:

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

# Buy Caverta said on May 28, 2007 4:09 PM:

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

# Buy Caverta said on May 29, 2007 12:30 AM:

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

# Mister said on June 2, 2007 7:47 PM:

You have very nice site!

http://campingwaterheaters.iespana.es

http://www.volny.cz/coachshoesitaly/

http://idisk.mac.com/louisvuittonsunglass/Public/index.html

http://amping-water-heaters.blogspot.com

# Lesbianh Sexu said on June 3, 2007 1:50 AM:

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

# Buy Caverta said on June 4, 2007 10:51 PM:

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

# Buy Caverta said on June 5, 2007 7:13 AM:

Hi Guys! What Your Site Powered By?

# Designer Handbagsy said on June 6, 2007 8:29 PM:

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

# Luk said on June 9, 2007 12:51 PM:

nice site!

http://idisk.mac.com/dtd4/Public/

http://pumacartshoes.iespana.es

# Bob said on June 26, 2007 9:41 AM:

adidas trail running shoes

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

louis vuitton cherry blossom handbags

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

# Ron said on July 2, 2007 7:04 PM:

You have very interesting site!

Respect you!

http://louisellipsehandbag.iespana.es

# kababdoul said on August 1, 2007 12:40 PM:

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.

# real estate c blog said on March 6, 2008 5:39 PM:

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

# credit cars info said on March 8, 2008 8:31 AM:

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

# Iyzreajy said on June 15, 2008 8:51 AM:

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

Anonymous comments are disabled
Page view tracker