Script SQL Server Database Using SQL Server Management Objects ( SMO ) and CaptureSql Mode - C# .NET 2.0
by David Hayden ( Sarasota Florida .NET Developer )
Filed: SQL Server Management Objects, SMO
More C# Code that I demostrated at the Orlando .NET Developer CodeCamp 2006. It shows you how to generate a script of a database in SQL Server using SQL Server Management Objects. There are a lot of options you can set. This justs accepts the defaults:
// Connect to Server
Server server = new Server(".");
// Set For Capture Mode Only
server.ConnectionContext.SqlExecutionModes
= SqlExecutionModes.CaptureSql;
// Get the Database to Transfer
Database db = server.Databases["Blog"];
// Setup transfer
Transfer t = new Transfer(db);
t.CopyAllObjects = true;
t.DropDestinationObjectsFirst = true;
t.CopySchema = true;
t.CopyData = true;
t.DestinationServer = ".";
t.DestinationDatabase = "Blog2";
t.Options.IncludeIfNotExists = true;
t.CreateTargetDatabase = true;
// Capture Transfer
StringCollection commands = t.ScriptTransfer();
// Get Script Into A String
StringBuilder sb = new StringBuilder();
foreach (string s in commands)
sb.Append(s);
string script = sb.ToString();
// Kill It
server = null;
You can read all my SQL Server Management Objects Articles and Tutorials.
Source: David Hayden ( Sarasota Florida .NET Developer )
Filed: SQL Server Management Objects, SMO