Skip to content

Instantly share code, notes, and snippets.

@SimonCropp
Created April 5, 2018 06:04
Show Gist options
  • Select an option

  • Save SimonCropp/93cca479eb7fb47e2283f348649d6fca to your computer and use it in GitHub Desktop.

Select an option

Save SimonCropp/93cca479eb7fb47e2283f348649d6fca to your computer and use it in GitHub Desktop.
generate script for sql server db
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
//using Microsoft.SqlServer.SqlManagementObjects package
public static class SqlScriptBuiler
{
public static string BuildScript(SqlConnection sqlConnection)
{
var builder = new SqlConnectionStringBuilder(sqlConnection.ConnectionString);
var theServer = new Server(new ServerConnection(sqlConnection));
var database = theServer.Databases[builder.InitialCatalog];
return string.Join("\n\n", GetScripts(database));
}
static IEnumerable<string> GetScripts(Database database)
{
foreach (var scriptable in GetScriptingObjects(database))
{
if (((dynamic) scriptable).IsSystemObject)
{
continue;
}
yield return Script(scriptable);
}
}
static string Script(IScriptable scriptable)
{
var options = new ScriptingOptions
{
ChangeTracking = true,
};
return string.Join("\n\n", scriptable.Script(options)
.Cast<string>()
.Where(ShouldInclude));
}
static IEnumerable<IScriptable> GetScriptingObjects(Database database)
{
foreach (Table table in database.Tables)
{
yield return table;
}
foreach (View view in database.Views)
{
yield return view;
}
foreach (StoredProcedure procedure in database.StoredProcedures)
{
yield return procedure;
}
}
static bool ShouldInclude(string script)
{
if (script == "SET ANSI_NULLS ON")
{
return false;
}
if (script == "SET QUOTED_IDENTIFIER ON")
{
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment