C#: Generate Scripts for database for SQL Server

— Generate Scripts for database objects with SMO for SQL Server

Generate Scripts for database objects with SMO for SQL Server

https://www.mssqltips.com/sqlservertip/1826/getting-started-with-sql-server-management-objects-smo/

 

/*working code*/

public void Main()public void Main()

{

ETLControlDetails etl =GetETLControlDetails();

GenerateDropTableScript(etl);

GenerateCreateTableScript(etl);

MessageBox.Show(sb.ToString());

}

/*working code*/

StringBuilder sb = new StringBuilder();

#region public struct ETLControlDetails
public struct ETLControlDetails
{
public string Server { get; set; }
public string SourceServer { get; set; }
public string SourceInstance { get; set; }
public string SourceDatabase { get; set; }
public string SourceSchema { get; set; }
public string SourceTable { get; set; }
}
#endregion

 

#region public ETLControlDetails GetETLControlDetails()
public ETLControlDetails GetETLControlDetails()
{

ETLControlDetails etl = new ETLControlDetails();
etl.Server = Dts.Variables[“User::SourceServer”].Value.ToString() + “\\” + Dts.Variables[“User::SourceInstance”].Value.ToString();
etl.SourceServer = Dts.Variables[“User::SourceServer”].Value.ToString();
etl.SourceInstance = Dts.Variables[“User::SourceInstance”].Value.ToString();
etl.SourceDatabase = Dts.Variables[“User::SourceDatabase”].Value.ToString();
etl.SourceSchema = Dts.Variables[“User::SourceSchema”].Value.ToString();
etl.SourceTable = Dts.Variables[“User::SourceTable”].Value.ToString();
return etl;
}
#endregion

#region public void ConnectToServer(string server)
public Server ConnectToServer(string server)
{
Server myServer = new Server(server);
try
{
/*Using windows authentication*/
myServer.ConnectionContext.LoginSecure = true;
myServer.ConnectionContext.Connect();
////
//Do your work
////
if (myServer.ConnectionContext.IsOpen)
myServer.ConnectionContext.Disconnect();
///*Using SQL Server authentication*/
//myServer.ConnectionContext.LoginSecure = false;
//myServer.ConnectionContext.Login = “SQLLogin”;
//myServer.ConnectionContext.Password = “entry@2008”;
LogInformation(“ConnectToServer”, String.Format(“Connected to the server {0}”, server));
}
catch (Exception e)
{
LogError(“ConnectToServer – Failed connecting to the server”, e);
}
return myServer;
}
#endregion

 

#region public void GenerateCreateTableScript(ETLControlDetails etl)
public void GenerateCreateTableScript(ETLControlDetails etl)
{
/*generate create table script for a individual table */
Server server = new Server(etl.Server);
Database db = server.Databases[etl.SourceDatabase.ToString()];
List<Urn> list = new List<Urn>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);

foreach (DataRow row in dataTable.Rows)
{
list.Add(new Urn((string)row[“Urn”]));
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.IncludeIfNotExists = true;
scripter.Options.SchemaQualify = true;
scripter.Options.SchemaQualifyForeignKeysReferences = true;
scripter.Options.NoCollation = true;
scripter.Options.DriAllConstraints = true;
scripter.Options.DriAll = true;
scripter.Options.DriAllKeys = true;
scripter.Options.DriIndexes = true;
scripter.Options.ClusteredIndexes = true;
scripter.Options.NonClusteredIndexes = true;
scripter.Options.ToFileOnly = true;
//scripter.Options.FileName = @”C:\Download\script_custom.sql”;
/*get the all the tables for a database*/
//scripter.Script(list.ToArray());

/*get a particular table script only*/
Table myTable = db.Tables[etl.SourceTable, etl.SourceSchema];
//scripter.Script(new Urn[] { myTable.Urn});

StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });
foreach (string script in sc)
{
sb.AppendLine();
sb.AppendLine(“–create table”);
sb.Append(script + “;”);
}
}
#endregion

 

#region public void GenerateCreateTableScript_V2(ETLControlDetails etl)
public void GenerateCreateTableScript_V2(ETLControlDetails etl)
{
//=================================================
Server myServer = ConnectToServer(etl.Server);

Scripter scripter = new Scripter(myServer);
Database db = myServer.Databases[etl.SourceDatabase.ToString()];

Table myTable = db.Tables[etl.SourceTable, etl.SourceSchema];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.IncludeHeaders = true;
scriptOptions.ScriptDrops = true;
scriptOptions.IncludeIfNotExists = true;
scriptOptions.WithDependencies = true;
scriptOptions.DriAll = true;
/* You can optionally choose each DRI object separately as given below */
scriptOptions.DriAllConstraints = true;
scriptOptions.DriAllKeys = true;
scriptOptions.DriChecks = true;
scriptOptions.DriClustered = true;
scriptOptions.DriDefaults = true;
scriptOptions.DriForeignKeys = true;
scriptOptions.DriIndexes = true;
scriptOptions.DriNonClustered = true;
scriptOptions.DriPrimaryKey = true;
scriptOptions.DriUniqueKeys = true;
scriptOptions.FileName = @”C:\Download\script_custom.sql”;

/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
{
sb.AppendLine();
sb.AppendLine(“–create table”);
sb.Append(script + “;”);
//MessageBox.Show(script);
}
/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
{
sb.AppendLine();
sb.AppendLine(“–create table”);
sb.Append(script + “;”);
//MessageBox.Show(script);
}
}
#endregion

 

#region public void GenerateDropTableScript(ETLControlDetails etl)
public void GenerateDropTableScript(ETLControlDetails etl)
{
/*generate drop table script for a individual table*/
Server server = new Server(etl.Server);
Database db = server.Databases[etl.SourceDatabase.ToString()];
List<Urn> list = new List<Urn>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);

foreach (DataRow row in dataTable.Rows)
{
list.Add(new Urn((string)row[“Urn”]));
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.IncludeIfNotExists = true;
scripter.Options.ScriptDrops = true;
scripter.Options.SchemaQualify = true;
//scripter.Options.FileName = @”C:\Download\script_custom.sql”;
/*get the all the tables for a database*/
//scripter.Script(list.ToArray());

/*get a particular table script only*/
Table myTable = db.Tables[etl.SourceTable, etl.SourceSchema];
//scripter.Script(new Urn[] { myTable.Urn });

StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });
foreach (string script in sc)
{
sb.AppendLine();
sb.AppendLine(“–script option”);
sb.Append(script + “;”);
}

}
#endregion

 

Source from online:

Problem
In my last article, Getting started with SQL Server Management Objects (SMO), I discussed what SMO is, how you can start working with SMO, how to connect to SQL server, how to enumerate through the different SQL objects, create a database, create a table etc, all programmatically.

In this tip I would like to take you on an SMO ride to generate SQL object scripts programmatically. Though you can do this through SQL Server Management Studio (SSMS) there might be times (more details on usage scenarios given below) when you would need to create SQL scripts automatically.

Solution
As I discussed in my last tip, SQL Server objects are represented as object hierarchies inside SMO, for example a Server object is a collection of Database objects. A Database object is a collection of a Table (though there are couple of other collection inside the Database object as well such as Stored Procedure, Views, User-defined Functions etc).  A Table  is a collection of a Column and so on.

Every object in this hierarchy has a method called a script, which returns a string collection of scripts. Apart from that, SMO provides a utility class, Scripter, which generates the script in a more efficient way. For example, the Scripter class can discover the relationships between objects and can provide scripts for dependencies as well and it can respond to Progress and Error events.

Usage Scenario

As I said, SQL Server Management Studio (SSMS) provides a wizard type interface to script out all or selected objects, but there might be some scenarios, some of them are discussed below, where you would consider the use of SMO instead of SSMS.

  • You want to create a tool which will automatically set up (or sync) an environment for dev or test which resembles the production environment.
  • You have a data warehouse database, in this database data is not that important (or even the data size is so big, taking a backup of the entire database would not be feasible) as data can again be pulled from the source systems but you want to make sure the schema objects are scripted and backed up automatically so that you can re-create the database in case of a disaster.
  • Programmatically you want to control the backup and restore process of database administration (I will cover this in more detail in another tip “Backup and Restore Programmatically with SMO”).
  • Programmatically you want to transfer a database schema and data to another instance of SQL Server. (I will cover this in more detail in another tip “Transferring schema objects and data programmatically with SMO”).

Example

Before you start writing your code using SMO, you need to take reference of several assemblies which contain different namespaces to work with SMO. For more details on what these assemblies are and how to reference them in your code, refer to my tip Getting started with SQL Server Management Objects (SMO).

C# Code Block 1 – Here I am using the Scripter utility class to generate the script for two selected databases. Two Databaseobjects are created first; one of them refers to the AdventureWorks database and another one refers to AdventureWorksDW.  The script method of the scripter object is called which takes database object URN (Unique Resource Name) as input and returns a string collection of scripts. URN is a new concept in SMO (this was not available in SQL-DMO) which provides similar notation like XPath to denote object hierarchy.

C# Code Block 1 – Generating Database Script

Scripter scripter = new Scripter(myServer);
Database myAdventureWorks = myServer.Databases[“AdventureWorks”];
Database myAdventureWorksDW = myServer.Databases[“AdventureWorksDW”];
Urn[] DatabaseURNs = new Urn[] { myAdventureWorks.Urn, myAdventureWorksDW.Urn };
StringCollection scriptCollection = scripter.Script(DatabaseURNs);
foreach (string script in scriptCollection)
Console.WriteLine(script);

C# Code Block 2 – In this code block I am generating CREATE TABLE scripts for all the tables in the AdventureWorks database. As said before, a database is a collection of tables, so I am enumerating through the table collection of the database to generate a script for each table. Along with that I am also using the ScriptOptions class to specify the different scripting options, for example in this code I am scripting IF NOT EXISTS and DROP TABLE scripts as well.

C# Code Block 2 – Generating scripts for table collection

Scripter scripter = new Scripter(myServer);

Database myAdventureWorks = myServer.Databases[“AdventureWorks”];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = true;
scriptOptions.IncludeIfNotExists = true;
foreach (Table myTable in myAdventureWorks.Tables)
{
/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
Console.WriteLine(script);

/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
Console.WriteLine(script);
}

C# Code Block 3 – This code block further extends the use of the Scripter and ScriptOptions classes to generate a script for a table (HumanResources.EmployeeAddress) along with all the other objects on which this table depends on. The ScriptOptionsclass also provides several properties for DRI (Declarative Referential Integrity) objects. You can either select individual DRI objects or all to script out along with the main object script.

C# Code Block 3
Generating table script with all dependencies and DRI objects

Scripter scripter = new Scripter(myServer);
Database myAdventureWorks = myServer.Databases[“AdventureWorks”];
Table myTable = myAdventureWorks.Tables[“EmployeeAddress”, “HumanResources”];/* Generate Scripts of table along with for all
* objects on which this table depends on */
ScriptingOptions scriptOptionsForDependendencies = new ScriptingOptions();
scriptOptionsForDependendencies.WithDependencies = true;
/* DriAll will include all DRI objects in the generated script. */
scriptOptionsForDependendencies.DriAll = true;
/* You can optionally choose each DRI object separately as given below */
//scriptOptionsForDependendencies.DriAllConstraints = true;
//scriptOptionsForDependendencies.DriAllKeys = true;
//scriptOptionsForDependendencies.DriChecks = true;
//scriptOptionsForDependendencies.DriClustered = true;
//scriptOptionsForDependendencies.DriDefaults = true;
//scriptOptionsForDependendencies.DriForeignKeys = true;
//scriptOptionsForDependendencies.DriIndexes = true;
//scriptOptionsForDependendencies.DriNonClustered = true;
//scriptOptionsForDependendencies.DriPrimaryKey = true;
//scriptOptionsForDependendencies.DriUniqueKeys = true;/* If you can use FileName to output generated script in a file
* Note : You need to have access on the specified location*/
scriptOptionsForDependendencies.FileName = @”D:\TableScriptWithDependencies.sql”;
StringCollection tableScripts = myTable.Script(scriptOptionsForDependendencies);
foreach (string script in tableScripts)
Console.WriteLine(script);

C# Code Block 4 – This code block provides CREATE TABLE scripts for all the AdventureWorks’ tables along with all the indexes of each table. Here I am using IndexCollection class to enumerate through index collection of the table to generate CREATE INDEX scripts for all the indexes on the given table.

C# Code Block 4
Generating scripts for table collection along with all the indexes on the table

Scripter scripter = new Scripter(myServer);
Database myAdventureWorks = myServer.Databases[“AdventureWorks”];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = true;
scriptOptions.IncludeIfNotExists = true;foreach (Table myTable in myAdventureWorks.Tables)
{
/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
Console.WriteLine(script);/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
Console.WriteLine(script);IndexCollection indexCol = myTable.Indexes;
foreach (Index myIndex in myTable.Indexes)
{
/* Generating IF EXISTS and DROP command for table indexes */
StringCollection indexScripts = myIndex.Script(scriptOptions);
foreach (string script in indexScripts)
Console.WriteLine(script);

/* Generating CREATE INDEX command for table indexes */
indexScripts = myIndex.Script();
foreach (string script in indexScripts)
Console.WriteLine(script);
}
}

C# Code Block 5 – In my last tip on SMO, I showed you how you can use SMO to create a database and a table on the server programmatically. In this code block, I am using the same code, but this time before creating the objects on the server I am generating database and table scripts. This means it is not required to create objects on the server in order to generate scripts, if you have objects in memory you can generate scripts for these objects as well even without creating on the server.

 

C# Code Block 5
Generating Script for objects in memory even before creating on the server

/* Create database called, “MyNewDatabase” */
Database myDatabase = new Database(myServer, “MyNewDatabase”);/* Output the database script on the console */
StringCollection DBScripts = myDatabase.Script();
foreach (string script in DBScripts)
Console.WriteLine(script);/* Create a table instance */
Table myEmpTable = new Table(myDatabase, “MyEmpTable”);
/* Add [EmpID] column to created table instance */
Column empID = new Column(myEmpTable, “EmpID”, DataType.Int);
empID.Identity = true;
myEmpTable.Columns.Add(empID);
/* Add another column [EmpName] to created table instance */
Column empName = new Column(myEmpTable, “EmpName”, DataType.VarChar(200));
empName.Nullable = true;
myEmpTable.Columns.Add(empName);
/* Add third column [DOJ] to created table instance with default constraint */
Column DOJ = new Column(myEmpTable, “DOJ”, DataType.DateTime);
DOJ.AddDefaultConstraint(); // you can specify constraint name here as well
DOJ.DefaultConstraint.Text = “GETDATE()”;
myEmpTable.Columns.Add(DOJ);
/* Add primary key index to the table */
Index primaryKeyIndex = new Index(myEmpTable, “PK_MyEmpTable”);
primaryKeyIndex.IndexKeyType = IndexKeyType.DriPrimaryKey;
primaryKeyIndex.IndexedColumns.Add(new IndexedColumn(primaryKeyIndex, “EmpID”));
myEmpTable.Indexes.Add(primaryKeyIndex);/* Output the table script on the console */
StringCollection TableScripts = myEmpTable.Script();
foreach (string script in TableScripts)
Console.WriteLine(script);

/* If you want to create objects on the server you need call
* create method or else objects will not be created on the server */
myDatabase.Create();
myEmpTable.Create();

Output:

The complete code listing (created on SQL Server 2008 and Visual Studio 2008, though there is not much difference if you are using it on SQL Server 2005 and Visual Studio 2005) can be found in the below text box.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s