I've been wondering if it's possible to create a database diagram by query instead of going through adding it manually in Management Studio.
Has anyone of you done this before?
The diagram functionality is entirely contained within Management Studio, and its internal API is undocumented. All diagrams are stored as a VARBINARY(MAX)
blob in sysdiagrams
, and the table and associated stored procedures are created only after you've given SSMS permission to do so. The format of the diagram blobs is likewise undocumented, but in case you're wondering, it's not something easy to reverse engineer, like an XML document, nor do the stored procedures touch the internal structure of the blob, so you can't learn anything from that either. Even if you did reverse engineer it, future versions of Management Studio might invalidate your findings (the format's been upgraded before).
I'm going to go with "no, this isn't possible for anyone who isn't a developer of Management Studio". If you want to programmatically create and maintain database diagrams (beyond renaming or dropping them), the native functionality of Management Studio isn't the way to go. Use one of the many other tools out there for diagramming.