About me

Michael L Perry

Improving Enterprises

Principal Consultant

@michaellperry

User login

Create a dependency map of SQL tables from foreign key constraints

A great tool for analyzing relationships is GraphViz. Install it and open up GvEdit. Now you can enter a text representation of a directed graph:

digraph "AdventureWorks2012_CS" {
  rankdir = BT
  ProductSubcategory -> ProductCategory
  Product -> ProductSubcategory
  Product -> UnitMeasure
}

Run the graph generator and it produces a nice visual representation.

The first line -- rankdir = BT -- tells GraphViz to rank items from bottom to top as it lays out dependencies. This makes all arrows point up. If you ever find an arrow pointing down, then that is part of a cycle.

To analyze a SQL schema, set your SQL output to text and run this query:

SELECT line FROM (
  SELECT
    'digraph "' + DB_NAME() + '" {' as line, 1 as position
  UNION SELECT
    ' rankdir = BT' as line, 2 as position
  UNION SELECT
    ' ' + FK.TABLE_NAME + ' -> ' + PK.TABLE_NAME as line, 3 as position
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
  UNION SELECT
    '}' as line, 4 as position
) l
ORDER BY position

Then copy the text output and paste into GvEdit. Now you have an overview of your SQL data model with related tables clustered together, and the high-level entities at the top.