Shahar Gvirtz's Weblog

Generating SQL Backup Script for Tables & Data from any .NET Application using SMO

What is SMO?

SMO, SQL Server Management Object, is a collection of objects that includes all you need to manage SQL Server from .NET applications. With SMO you can manage pretty much everything – from databases, tables, stored procedures, jobs – you name it.

Actually, SMO is “.NET Version” of COM object known as SQL-DMO (SQL Distributed Management Objects).

SMO Assemblies (dll’s) can usually be found at: C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ (for SQL Server 2008).

What We’re Going To Do?

In this post I’ll show an easy way to write a method that generates SQL File that include backup of both the schema and the data of specific tables (CREATE statements for each table and INSERT statements for all the data). Same as if you right-click on DB name at SQL Server Management Studio and choose “Generate Scripts”

The Method

First, we’ll have to add references to the following assemblies:

  1. Microsoft.SqlServer.ConnectionInfo
  2. Microsoft.SqlServer.Management.Sdk.Sfc
  3. Microsoft.SqlServer.Smo

[All of them can be found in the directory I mentioned before, with the same name as in the list just with “.dll” in the end]

In the following example, we want to backup specific tables (we know the tables names) that are in a specific DB. This is how our method will look:

   1: public static void Backup(string FileName, string[] Tables)
   2: {
   3:     StringBuilder sb = new StringBuilder();
   4:     Server srv = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection("<db name>", "<user name>", "<password>"));
   5:     Database dbs = srv.Databases["<db name>"];
   6:     ScriptingOptions options = new ScriptingOptions();
   7:     options.ScriptData = true;
   8:     options.ScriptDrops = false;
   9:     options.FileName = FileName;
  10:     options.EnforceScriptingOptions = true;
  11:     options.ScriptSchema = true;
  12:     options.IncludeHeaders = true;
  13:     options.AppendToFile = true;
  14:     options.Indexes = true;
  15:     options.WithDependencies = true;
  16:     foreach (var tbl in Tables)
  17:     {
  18:         dbs.Tables[tbl].EnumScript(options);
  19:     }
  20: }

Our method get two parameters. The first one is the Full path to the file we want to export, and the second is an array with name of the tables we want to generate SQL backup script for.

In line 4 you can see that there is a new instance of “Server” object that represents the SQL Server itself.

In line 5 choose the DB that we want (Pay attention to add Exception handling if you going to use this code).

Then, from line 6 to 15 we set some properties in the ScriptingOptions object that includes our settings for the script generation. In this example, i backup both data and schema so ScriptData and ScriptSchema are both true.

I also backup the Indexes. And, in this example, i set WithDependencies property as true which means that the generated script will include CREATE statements for tables that are somehow related to the tables we actually backup. For example, if table A has FK to table B and I’ll backup table A with this method, it’ll also generates the SQL Statements to backup table B.
You can find the full documentation of all the available settings here.

In lines 15-18 we iterate the array we get as a parameter to the method and for each table call Table.EnumScript method thet get ScriptiongOptions instance as parameter (which includes all the settings). This method also returns a collection of strings (IEnumerable<string>) that includes the generated SQL.

In this example i Ignore the returned value because i set the property ScriptiongOptions.FileName to a path for a file where the SQL will be saved, so i don’t need the collection in the code (know that because i call EnumScript several times, for each table, it’s important to set ScriptingOptions.AppendToFile as true or we’ll override the file each time).

The Difference Between EnumScript and Script

If you’ll take a look in the documentation you’ll see that there is also method called Script that we can use with Table object. So why don’t I use it?

The reason (which i couldn’t find in the official documentation) is that if we set in the ScriptingOptions object we pass to the method ScriptiongOptions.ScriptData = true we must use EnumScript because Script will give us the following Exception:

“This method does not support scripting data”.

Summary

In order to work with SQL Server from .NET Applications we have SMO components.
We can generate SQL statements that can be used to backup table (create table and insert data) with Table.EnumScript method, and we can give the settings we want with ScriptingOptions object.

Shahar.

Comments

Valamas said:

Fantastic, thank you

# March 3, 2010 7:04 PM

compacttreadmill said:

Hmmm, you're the expert. Thank you.

# March 4, 2010 1:25 AM

Generating SQL Backup Script for Tables & Data from any .NET Application using SMO – Shahar Gvirtz’s Weblog | Head.SmackOnTable(); said:

Pingback from  Generating SQL Backup Script for Tables &amp; Data from any .NET Application using SMO &#8211; Shahar Gvirtz&#8217;s Weblog | Head.SmackOnTable();

# March 7, 2010 3:52 PM

Peter said:

dbs.Tables[tbl].EnumScript(options);

Throwes me an FailedOperationException

Script failed for Table 'dbo.TableName'.

Anybody has the same problem? This table only contains 2 columns (smallint, bit).

# July 19, 2010 6:42 AM

asdf said:

What can i do with the IEnumerable?

I want it to make an sql file with the tables insert script.

# September 7, 2010 9:37 AM

svkn said:

Great article. thanks to share. Where i need to put the server name "localhost"

# May 27, 2011 2:45 PM

Flour Milling Equipment said:

I never read whole articles but the way you wrote this information is simply amazing and this kept my interest in reading and I enjoyed it. I read your post and I found it amazing. Your thought process is wonderful.

# June 10, 2011 3:55 AM

pellet mill said:

I find your website on google, it proved to be useful for me , i like it very much !

# June 13, 2011 4:54 AM

Pellet Mill said:

I never read whole articles but the way you wrote this information is simply amazing and this kept my interest in reading and I enjoyed it. I read your post and I found it amazing. Your thought process is wonderful.

# June 13, 2011 4:58 AM

Testking 70-662 said:

Articles makes a website more attractive and powerful by their content. So, always keep sharing your new ideas. And everyone has right to speak.

# June 27, 2011 8:04 AM

Printing Presentation Folders said:

You have again come with very good and unique information. Keep it up man and continue on providing such valuable information with us. <a href="www.emanprinting.com/.../Printed-Presentation-Folders.php">Printed Presentation Folders</a>

# July 4, 2011 6:22 AM

NIranjan said:

Hello.. can anyone update the insert script generation code through smo or copying one table data to another using server management objects.

http://www.niranjankala.in

# July 26, 2011 6:28 AM

jessica parker perfume said:

After reading the article, I feel that I need more information on the topic. Can you suggest some resources please?, Excellent post!

# August 5, 2011 1:35 PM

Testking 350-001 said:

Interesting one,Every innovation have solutions of previous shortcomings.Thanks for updating me.<a href="www.certsquare.com/.../70-640.php">Testking 70-640</a>

# August 14, 2011 12:45 AM

samurai swords said:

Exceptional post! I've bookmarked your website as well due to the fact I discovered it is seriously educational and I enjoyed reading your posts.

# September 5, 2011 1:09 PM

Birthday Sms said:

I love this type of web sites very much

this is very informative web site.

# September 22, 2011 8:28 AM

Kishan Gusani said:

hiiii,,,,,its nice article and very much useful...

hii  ....Peter just give the filename as....

@"D:\TableScriptWithDependencies.sql"...,,,

and u would b much plesant to get d output you want,,.

Preety Cool,,,..

# October 11, 2011 4:16 PM

roshil said:

Great article..

I need to  take the script of my tables with some conditions.

1.My all table have one bit field named 'Status' and i need to take the script of the data with Status='true'.(insert statements for the records with source='true')

2.I have some master tables in my database.Sio i took the script with 'WithDependencies=true'.So it takes script of each tables one by one and append it to one file.But for some insert statement duplicate is coming.how can i avoid that?

Please help me.

Thanks in advance.

Roshil K

# October 13, 2011 12:54 AM

Red Bull Hats said:

I am sure to all the commenters here!

# October 13, 2011 3:13 AM

beef recipes said:

I read your posting thanks!!!

# October 19, 2011 1:58 AM

christmas greetings text said:

Then, from line 6 to 15, we set some properties in the options of our script object containing options for generating script. In this example, I save the data and schema, so the script and the data are both ScriptSchema true.

# November 29, 2011 7:29 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)