SQL Server Table Relationship

SQL Server Mgmt Studio 2005: can someone please help me understand how to view and print relationships between tables by showing columns in tables. I did it many years ago and many days have been fighting for it.

+4
source share
3 answers

Right-click the database name, expand Database Charts, and select New Database Chart.

+7
source

You need to create and edit a database diagram, see this Getting Started with SQL Server Database Diagrams and / or Designing Database Diagrams

you can do this with a query: SQL SERVER - a query to display external relationships and a constraint name for each table in the database

here is the query that PK, Check Constraints and FKs will get to and from @TableName with a few column restrictions in a comma-separated list:

DECLARE @TableName varchar(250) SET @TableName='YourTable' ;WITH AllInfo AS ( SELECT tc.TABLE_NAME,tc.CONSTRAINT_NAME, ccu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.TABLE_NAME =@TableName UNION SELECT FK.TABLE_NAME,C.CONSTRAINT_NAME,CU.COLUMN_NAME 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 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN (SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE PK.TABLE_NAME=@TableName ) SELECT DISTINCT t1.TABLE_NAME,t1.CONSTRAINT_NAME ,STUFF( (SELECT ', ' + t2.COLUMN_NAME FROM AllInfo t2 WHERE t1.TABLE_NAME=t2.TABLE_NAME AND t1.CONSTRAINT_NAME=t2.CONSTRAINT_NAME ORDER BY t2.COLUMN_NAME FOR XML PATH(''), TYPE ).value('.','varchar(max)') ,1,2, '' ) AS ColumnNames FROM AllInfo t1 ORDER BY 1,2,3 
+3
source

You can create a database diagram and add all your tables to it. This will be a graphical representation if that is what you want.

0
source

All Articles