How can I export SQL Server database diagrams as developer-friendly SQL scripts?
By developer-friendly, I mean written in a way similar to the way a human would write them as opposed to the messy many-UPDATE
s style used by existing solutions.
(Note that similar questions on this site only seem to cover specific versions of SQL Server or migration of diagrams.)
Here's a script to do this. Tested in SQL Server 2008 R2 and 2012.
It basically exports the contents of the
sysdiagrams
table. Note that it does not retain the diagrams' id numbers. It also retains who created the diagrams, but the id number should also exist in the target database.If you run the resultant script on a server instance that doesn't have the database diagramming objects, it should still work. However, after doing this, in order for them to appear in SSMS, I think you'll need to expand the Database Diagrams node and click Yes when asked to create them.
This is based on the 2008 script from here.
Note that there is a catch! SSMS and other Microsoft tools truncate the resulting text in the result set if you have more than a few diagrams. To get the full text, here's a PowerShell script to run the query and put the output in the clipboard:
Fill in the database, instance name, and SQL placeholders.