Skip to content

Instantly share code, notes, and snippets.

@ryanrousseau
Last active October 30, 2015 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanrousseau/ed3162537bcd00b47622 to your computer and use it in GitHub Desktop.
Save ryanrousseau/ed3162537bcd00b47622 to your computer and use it in GitHub Desktop.
#load "scriptTables.csx
ScriptTables("server", "db", "targetDirectoryPath");
#r "Microsoft.SqlServer.ConnectionInfo"
#r "Microsoft.SqlServer.Smo"
#r "Microsoft.SqlServer.Management.Sdk.Sfc"
using Microsoft.SqlServer.Management.Smo;
void ScriptTables(string serverName, string databaseName, string targetDirectory)
{
var options = new ScriptingOptions();
options.AnsiFile = true;
options.DriChecks = true;
options.DriDefaults = true;
options.DriForeignKeys = true;
options.DriPrimaryKey = true;
options.DriUniqueKeys = true;
options.ExtendedProperties = true;
options.IncludeDatabaseContext = false;
options.ScriptDataCompression = false;
options.ToFileOnly = true;
ScriptTables(serverName, databaseName, targetDirectory, options);
}
void ScriptTables(string serverName, string databaseName, string targetDirectory, ScriptingOptions options)
{
var server = new Server(serverName);
var db = server.Databases[databaseName];
var scripter = new Scripter(server);
scripter.Options = options;
var originalDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(targetDirectory);
foreach(Table table in db.Tables)
{
if (table.IsSystemObject) continue;
var urn = table.Urn;
var tableName = table.ToString().Replace("[", "").Replace("]", "") + ".sql";
scripter.Options.FileName = tableName;
scripter.Script(new [] { urn });
}
Directory.SetCurrentDirectory(originalDirectory);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment