Last active
October 30, 2015 02:31
-
-
Save ryanrousseau/ed3162537bcd00b47622 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#load "scriptTables.csx | |
ScriptTables("server", "db", "targetDirectoryPath"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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