Scripting a database objects from development environment is a necessary step before deployment to production or test environments and to add the script to source control. Doing this manually is error prone and time consuming.
Also If you practice continuous integration, it's a must to automate the script generation process.
I used
Database Publishing Wizard which is hosted on codeplex. It's good but the command line options lack the ability to determine which objects to script. That caused a problem because it scripted users as well. Which I did not want it to do.
Although it's hosted on
codeplex, I could not download the source code to make the necessary modifications.
So, I had to go the hard way. And I did it myself. Using
SQL Server Management Objects (SMO), I built a small command line utility to script: Tables, Indexes, UDFs, Veiws, SPs, Defaults, Checks, Foreign keys.
There are limitations ofcourse, But at least it's under control as long as the code is available.
The application depends on the core class ScriptingEngine, which in turn depends on Microsoft.SqlServer.Management.Smo.Scripter class.
Points of interest:
- Order of scripting is important for the script to be used to regenerate objects.
- Determining object dependencies is an important trick. Using DiscoverDependencies method, it's possible to order objects bu
public void ScriptViews()
{
List<urn> urns=new List<urn>();
foreach (View view in _database.Views)
{
if (view.IsSystemObject)
continue;
urns.Add(view.Urn);
}
DependencyTree tree = _scripter.DiscoverDependencies(urns.ToArray(), true);
DependencyCollection dc = _scripter.WalkDependencies(tree);
RemoveUrnType(dc,"Table");
RemoveUrnType(dc, "UserDefinedFunction");
_scripter.ScriptWithList(dc);
}
- Note the RemoveUrnType method, it's used to filter unwanted object types from the DependencyCollection:
private void RemoveUrnType(DependencyCollection dc,string type)
{
for (int counter = 0; counter < dc.Count; counter++)
{
if (dc[counter].Urn.Type==type)
{
dc.RemoveAt(counter);
counter--;
}
}
}
SqlScripter.exe -server:
server\
instance -database:
dbname -login:login -password:
pwd -filename:
pathtoscriptfileYou can download the source from skydrive: