Click here to Skip to main content
6,292,426 members and growing! (9,915 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

SMO - Manage your SQL Server!

By Thomas Haller

A quick start tutorial on how to manage your Microsoft SQL Server 2000/2005 with C# and the Microsoft's SQL Server Management Objects (SMO)
C#, Windows, .NET, Visual Studio, DBA, Dev
Posted:11 Apr 2006
Updated:31 May 2006
Views:71,814
Bookmarked:74 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
24 votes for this article.
Popularity: 4.63 Rating: 3.36 out of 5
1 vote, 4.2%
1
3 votes, 12.5%
2
5 votes, 20.8%
3
7 votes, 29.2%
4
8 votes, 33.3%
5

Sample Image - SMODemo.jpg

Introduction

May I introduce you to SMO, the Framework provided by Microsoft to manage your MS SQL Servers? This Article is a quick start tutorial. SMO is a replacement of the SQL-DMO - it's now managed code and it now supports the features of the SQL Server 2005 now. The intention of this article is to show what SMO is, explain some basic steps, and to make you hungry for more.

Advantages
.NET: Use your well known framework to develop your SQL Server applications.
OOP: Its much easier to browse the object hierarchy with IntelliSense than browsing the hundreds of stored procedures
Exceptions: SMO uses exceptions in an exemplary way.

Disadvantages
Requires .Net Framework to be installed on the client PC
Works only with Microsoft SQL Servers
Needs SMO to be installed

Note that most (or even all) features provided by the SMO are also available as stored procedures on the SQL Server. So you could say the SMO is a wrapper for the stored procedures on the SQL Server.

Systemrequirements

.Net Framework 2.0
SQL Server 2000 or 2005 (NOTE: SMO Supports features that are new in SQL Server 2005 and do not work with SQL Server 2000)
SMO needs to be installed.

Skillrequirements

Basic C# knowledge + Windows Forms
Basic SQL Server knowledge
About 30 minutes of time

Adding a Reference to SMO

To use the SMO, you have to add it as a Reference to your Project. This Screenshots has been made with Visual Studio 2005 Express Edition.



Solution Browser - > References -> Add Reference


Select SQL Server Components and Hit OK.

Getting Connected

The first thing we have to do is to make a connection to our server.
Now you might be thinking "Hey, there is already a class existing to connect to a SQL Server - System.Data.SqlClient.SqlConnection", and you are all right - you can use this class to build your connection to the Sql Server.

Microsoft.SqlServer.Management.Smo.Server server;
///  <summary>
/// Initializes the field 'server'
/// </summary> 
void InitializeServer()
{
    // To Connect to our SQL Server - 
    // we Can use the Connection from the System.Data.SqlClient Namespace.
    SqlConnection sqlConnection = 
      new SqlConnection(@"Integrated Security=SSPI; Data Source=(local)\SQLEXPRESS");

    //build a "serverConnection" with the information of the "sqlConnection"
    Microsoft.SqlServer.Management.Common.ServerConnection serverConnection = 
      new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);

    //The "serverConnection is used in the ctor of the Server.
    server = new Server(serverConnection);
}

Object Hierarchy

Once you have got a connection to your server - accessing databases is very simple. Most of the SMO Objects are stored in a Parent/Child Collection ownership.
A Server has got a collection of Databases (The Databases Parent is the Server),
A Database has got a collection of Tables,
A Table has got a collection of Columns.....

//this Code adds a all known Databases to a Listview

//clean up the listview first.
listView1.Clear();
listView1.Columns.Clear();

//building the Coloumns
listView1.Columns.Add("Name");
listView1.Columns.Add("# of Tables");
listView1.Columns.Add("Size");

//iterate over all Databases
foreach( Database db in server.Databases )
{
    //add the Data to the listview.
    ListViewItem item = listView1.Items.Add(db.Name);
    item.SubItems.Add( db.Tables.Count.ToString() );
    item.SubItems.Add(db.Size.ToString());
}

This Code shows how to enlisting Backup Devices

listView1.Clear();
listView1.Columns.Clear();

listView1.Columns.Add("Name");
listView1.Columns.Add("Location");

foreach (BackupDevice backupDevice in server.BackupDevices)
{
    ListViewItem item = listView1.Items.Add(backupDevice.Name);
    item.SubItems.Add(backupDevice.PhysicalLocation);
}

Create a new Database

Of course - we are not limited to getting information about our SQL Server - we can also create, drop and alter objects. Most SMO objects have 2 requirements - a valid (unique) Name and a valid Parent.

database.Name = dbName.Text;
database.Parent = server;
database.Create();

You see - SMO uses really compact code :-) Now - lets Create a Backup Device.

backupDevice.Parent = Server;
backupDevice.Name = "myBackupDevice";
backupDevice.PhysicalLocation = @"C:\myNewBackupDevice.bak";
backupDevice.BackupDeviceType = BackupDeviceType.Disk;
backupDevice.Create();

Scripting with T-SQL!

In some cases you might want to have a T-SQL Script of a operation. Let's take the example from above - we want a script for adding a Backup Device to our SQL Server.

backupDevice.Parent = Server;
backupDevice.Name = "myBackupDevice";
backupDevice.PhysicalLocation = @"C:\myNewBackupDevice.bak";
backupDevice.BackupDeviceType = BackupDeviceType.Disk;
StringCollection strings =  backupDevice.Script();
//results:
// strings [0] = "EXEC master.dbo.sp_addumpdevice  @devtype = N'disk',
// @logicalname = N'myBackupDevice', @physicalname = N'C:\myNewBackupDevice.bak'"

Doing a Backup

Finally, i want to show you how to do a Backup of your Database. Note that the class Backup doesn't represent a BackupDevice - it represents a "Backup Operation".
Backup backup = new Backup();
//we asume that there is a Logical Device with the Name "myBackupDevice"
backup.Devices.AddDevice("myBackupDevice", DeviceType.LogicalDevice);
backup.Database = "Master";
backup.SqlBackup(server);

Additional Features

The functional range of SMO is amazing!
SMO supports really everything you will need.
Indexes,
Constraints,
Relationships,
Permissions
Stored Procedures,
Full Text Catalogues,
HTTP Protocol,
Triggers,
Mirroring,
Replication,
Asymmetric Encryption,
.
.
.

In short:
Everything you desire :)
And if you understand the basics of a specific feature, you won't have problems to implement it with SMO.

History

  • 04/11/06 - First Version of article
  • 04/12/06 - Fixed wrong requirements (thx to akosows) - Added hint for SQL-DMO
  • 05/31/06 - Minor changes


Thank you for reading my article, comments and critiques are very welcome!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Thomas Haller


Member
Thomas (23) , living in austria, is a Softwaredevelopment beginner, who hopes that he is on the best way to become a professional. He started software development at the age of 16 with Delphi. He is very often unsure about what is the best for him - so he changed technology very often - starting with Delphi - switched to Networking - tryed Web Development with HTML-CSS-PHP-MySql - back to Windows Programming with VB - uh Databases are Fun Smile - C/C++ - MFC - COM.... Now, thinks the .NET Enviroment is the best for him, so he passed the MCP Exams for C# Windows Forms and Designing SQL Server 2000 Databases this year - moving forward to become a MCAD.
Occupation: Web Developer
Location: Austria Austria

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
Generali am using EZManage SQL Pro to manage and backup all my sql server Pinmemberitayl4:13 27 May '09  
GeneralLicense of SMO Pinmemberlorecasas8:59 17 May '08  
GeneralRe: License of SMO Pinmemberalhambra-eidos22:35 6 Oct '08  
GeneralRe: License of SMO PinmemberLambin21:12 6 Apr '09  
GeneralServer for Backup Pinmemberlorecasas8:56 17 May '08  
GeneralDropping Stored Procs Pinmemberblacklocist9:40 18 Oct '07  
GeneralRe: Dropping Stored Procs Pinmemberblacklocist9:45 18 Oct '07  
GeneralRe: Dropping Stored Procs Pinmemberblacklocist10:58 18 Oct '07  
GeneralRe: Dropping Stored Procs PinmemberThomas Haller11:17 18 Oct '07  
GeneralRe: Dropping Stored Procs Pinmemberblacklocist5:33 19 Oct '07  
GeneralRe: Dropping Stored Procs PinmemberThomas Haller8:56 19 Oct '07  
GeneralError running demo PinmemberMarkChimes20:23 6 Feb '07  
GeneralRe: Error running demo PinmemberMarkChimes20:38 6 Feb '07  
GeneralFind Relation between two table Pinmemberatefeh mokhtary21:03 26 Nov '06  
GeneralSql Transaction Pinmembervalamas_salmat15:35 19 Nov '06  
GeneralProblems to create a DB [modified] PinmemberDark_leon0:16 12 Jun '06  
GeneralRe: Problems to create a DB PinmemberDark_leon0:47 12 Jun '06  
GeneralRequirements on System Pinmemberakosows23:25 11 Apr '06  
GeneralRe: Requirements on System PinmemberThomas Haller4:14 12 Apr '06  
GeneralRe: Requirements on System Pinmemberalhambra-eidos22:40 6 Oct '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 31 May 2006
Editor:
Copyright 2006 by Thomas Haller
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project