Created
November 19, 2018 02:08
-
-
Save AtomicBlom/3b191f2ba09e5eb2c941f1cea44659c4 to your computer and use it in GitHub Desktop.
Create a SQL script that will restore your diagrams created in SSMS.
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
//Specify a filename location if you want to save the file. | |
string filename = null; | |
//Set this to a DbSet, DbTable or whatever you are using to access [dbo].[SysDiagrams] for your database. | |
var sysDiagramsSource = Sysdiagrams; | |
var diagramDefinition = from diagram in sysDiagramsSource | |
select new | |
{ | |
Name = diagram.Name, | |
diagram.Principal_id, | |
diagram.Version, | |
diagram.Definition | |
}; | |
// These bytes don't seem to exist in the definition when you select it, but are needed when creating? | |
// Failing to append these bytes results in an error | |
var footerBytes = new byte[] { | |
0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, | |
0, 98, 136, 82, 20 | |
}; | |
var footer = BitConverter.ToString(footerBytes).Replace("-", ""); | |
var bytesPerLine = 96; | |
var diagramSqlQueries = from d in diagramDefinition.ToList() | |
//Split the definition over many lines, Many IDEs don't handle unbounded horizontal scrolling well. | |
let definition = BitConverter.ToString(d.Definition.ToArray()).Replace("-", "") | |
let splitDefinition = string.Join("\\\r\n", Enumerable.Range(0, definition.Length / bytesPerLine).Select(i => definition.Substring(i * bytesPerLine, bytesPerLine))) | |
select $@" | |
exec dbo.sp_creatediagram | |
@diagramname = '{d.Name}', | |
@owner_id = null, | |
@version = {d.Version}, | |
@definition = 0x\ | |
{splitDefinition}\ | |
{footer}"; | |
foreach (var diagramQuery in diagramSqlQueries) { | |
diagramQuery.Dump(); | |
} | |
if (filename != null) | |
{ | |
File.WriteAllLines(filename, diagramSqlQueries); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment