One of the most common actions developers need to perform is the scripting of databases for archiving, distribution and installation purposes. Sql Server has the capability to script databases, but it is not complete. Scripting table data as insert statements is not offered, and because Of this the process of scripting an entire database "in one shot" Becomes Quite Cumbersome.
Not long ago, the nice people from Redmond put out a very useful ASP.NET web application entititled "Sql Web Data Administrator". Without spending a lot of time to explain, in case you have not seen it, it is basically a web -BASED Enterprise Manager Clone for SQL Server 2000 and MSDE Databases.
Now one of the most interesting things you'll find with this, if you get far enough to start snooping around the generously - provided source code, is the fact that the web-based front end uses an assembly called "SQLAdmin.dll", Which is essentially a managed code wrapper over the maximtant parts of the the object hierarchy of sqladmin locks Like:
As can be plainly seen, somebody spent a lot of very thoughtful time entity-izing all the SQLDMO database objects, thus making advanced managed - code SQL Server scripting and administration a breeze for anyone who is willing to take the time to use it.
To that end, I decided to put together a Windows Forms front end to enable easy database export scripting in a manner similar to the way the web-based app offers it, but without the dependency on having it installed as a web application. The UI To My Creation Looks Like So:
When you TAB out of the Password field, it populates the list of Databases on the chosen server. At this point, one only needs to select a database, uncheck any of the Scripting options that are not desired, and hit the EXPORT! Button . A progress bar will increment while the scripting is being completed, and a Save File Dialog will come up, allowing you to save your SQL script wherever you want. Best of all, it will be a script for the ENTIRE DATABASE, INCLUDING TABLE DATA ! Here's what the main method Looks like, Under the hood:
Private void ExportButton_Click (Object Sender, System.Eventargs E)
{
LBLRESULT.TEXT = ""
String DatabaseName = (String) ExportDatabaseElist.selectedItem.toString ();
Bool scriptdatabase = chkdatabase.checked;
Bool scriptdrop = this.chkdropcommands.checked;
Bool scripttableschema = this.chktables. ..CHECKED;
Bool scripttabledata = this.chktabledata.checked;
Bool script storedprocedures = this.chkstoredProcs.checked;
Bool scriptcomments = this.chkdescriptivecomments.checked;
SQLServer Server = new SQL Server (this.txtServer.Text, this.txtusername.text, this.txtpassword.text);
Server.Connect ();
SqlDatabase Database = Server.Databases [DatabaseName];
IF (Database == Null)
{
Server.disconnect ();
// Database Doesn't Exist - Break Out and Go To Error Page
MessageBox.show ("Connection Error");
Return;
}
SQLTableCollection Tables = Database.tables;
SQLSToredProcedureCollection sprocs = database.storedProcedures;
Stringbuilder scriptResult = new stringbuilder ();
ScriptResult.ensureCapacity (400000);
ScriptResult.Append (String.format ("/ * generated on {0} * // r / n / r / n", datetime.now.tostring ())); scriptResult.append ("/ * options selected:") ;
IF (scriptdatabase) scriptresult.append ("database");
IF (scriptdrop) scriptResult.Append ("Drop-Commands");
IF (ScriptTablesChema) ScriptResult.Append ("Table-Schema");
IF (ScriptTableData) ScriptResult.Append ("Table-Data");
IF (ScriptStoredProcedures) ScriptResult.Append ("Stored-Procedures");
IF (scriptcomments) scriptResult.append ("comments");
ScriptResult.Append ("* // r / n / r / n");
// script flow:
// Drop and Create Database
// USE [database]
// GO
// Drop Sprocs
// Drop Tables
// CREATE TABLES without constraints
// Add Table Data
// Add Table Constraints
// CREATE SPROCS
// Drop and Create Database
ScriptDatabase
ScriptResult.Append (Database.script)
SQLScriptType.create |
(scriptdrop? SQLScriptType.drop: 0) |
(ScriptComments? SQLScriptType.comments: 0))))))))
// USE DATABASE
ScriptResult.Append (String.Format ("/ R / NUSE [{0}] / R / NGO / R / N / R / N", DatabaseName));
ProgressBar1.Value = 20;
Progressbar1.refresh ();
// Drop Stored Procedures
ScriptStoredProcedures && scriptdroP)
{
For (int i = 0; i { IF (sprocs [i] .storedProceduRetyPE == SQLOBJECTTYPE.USER) { ScriptResult.Append (sprocs [i] .script (SQLScriptType.drop | (Scriptcomments? SQLScriptType.comments: 0)))))))) } } } ProgressBar1.Value = 30; Progressbar1.refresh (); // Drop Tables (this include Schamas and Data) IF (ScriptTableschema && Scriptdrop) { For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptschema (SQLScriptType.drop | (Scriptcomments? SqlscriptType.comments: 0)))); } } } ProgressBar1.Value = 40; Progressbar1.refresh (); // Create Table Schemas IF (scripttableschema) { // first create Tables with no constraints For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptschema (SqlscriptType.create | (ScriptComments? SQLScriptType.comments: 0))))) } } } ProgressBar1.Value = 50; Progressbar1.refresh (); // CREATE TABLE DATA IF (scripttabledata) { For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptdata (scriptcomments? sqlscripttype.comments: 0)); } } } ProgressBar1.Value = 60; Progressbar1.refresh (); IF (scripttableschema) { // Add defaults, Primary Key, And Checks For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptsChema (SqlscriptType.defaults | SQLScriptType.PrimaryKey | SQLScriptType.Checks | (Scriptcomments? SQLScriptType.comments: 0)))); } } // Add foreign Keys For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptsChema (SQLScriptType.ForeIgnys | (Scriptcomments? SQLScriptType.comments: 0))))) } } ProgressBar1.Value = 70; Progressbar1.refresh (); // Add unique keys For (int i = 0; i { IF (Tables [i] .tabletype == sqlobjecttype.user) { ScriptResult.Append (Tables [i] .scriptsChema (SQLScriptType.uniqueKeys | (Scriptcomments: 0)))))))); } } // Add indexes For (int i = 0; i { IF (Tables [i] .TableType == SqlobjectType.user) { ScriptResult.Append (Tables [i] .scriptschema (SQLScriptType.indexes | (ScriptComments: 0)))))))) } } } ProgressBar1.Value = 80; Progressbar1.refresh (); // Create Stored Procedures ScriptStoredProcedures) { String tmpResult = string.empty; For (int i = 0; i { IF (sprocs [i] .storedProceduRetyPE == SQLOBJECTTYPE.USER) { TMPRESULT = SPROCS [I] .script (SQLScriptType.create | (ScriptComments? SQLScriptType.comments: 0))); ScriptResult.Append (TMPRESULT); TMPRESULT = "" } } } Server.disconnect (); ProgressBar1.Value = 100; Progressbar1.refresh (); ScriptResult.Append ("/ * ----- end script ------ * /"); SavefileDialog1.filter = "SQL Files (* .sql) | * .sql | all files (*. *) | *. *"; SavefileDialog1.restoreDirectory = true; Stream MyStream; String thecontent = scriptResult.toString (); IF (SavefileDialog1.ShowDialog () == DialogResult.ok) { IF ((MyStream = SavefileDialog1.OpenFile ())! = null) { Streamwriter wtext = new streamwriter; WTEXT.WRITE (THECONTENT); WTEXT.FLUSH (); MyStream.close (); LBLRESULT.TEXT = "File Saved!"; } } } IHOPE You Enjoy The SQL Database Export Utility, And That IT Helps You To Grow and Think "Outside The Box". Full Source Code Is Available In The Solution Download Below.