Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help with Foreign Key Column & Entity Relationship

Author  Topic 

eastwest
Starting Member

3 Posts

Posted - 2009-09-26 : 18:16:26
Hello All,

In a organization where I just started working, they have SQL Server 2000 database and upgrading to SQL Server 2008.

We have huge number of tables in a database & most of the tables has like 75 columns in it. And we don't have any Entity Relationship diagram.

I want to determine which column in a particular table is a foreign key column to which table. Also I would like to have an ER diagram created for the database, how I can achieve this.

I am new to SQL Server database. Any help will be greatly appreciated.

Thank You


winterh
Posting Yak Master

127 Posts

Posted - 2009-09-28 : 09:44:05
You are in some deep doo-doo

[ /fail at query]
Go to Top of Page

rohitkumar
Constraint Violating Yak Guru

472 Posts

Posted - 2009-09-28 : 16:49:40
answer to your first question

SELECT FK.NAME AS CONSTRAINT_NAME
, PT.NAME AS PARENT_TABLE
, PC.COLUMN_ID AS PARENT_COLUMN_ID
, PC.NAME AS PARENT_COLUMN_NAME
, RT.NAME AS REFERENCED_TABLE
, RC.COLUMN_ID AS REFERENCED_COLUMN_ID
, RC.NAME AS REFERENCED_COLUMN_NAME
FROM sys.foreign_keys FK
JOIN sys.foreign_key_columns FKC ON FKC.CONSTRAINT_OBJECT_ID = FK.OBJECT_ID
JOIN SYS.TABLES PT ON PT.OBJECT_ID = FK.PARENT_OBJECT_ID
-- AND PT.OBJECT_ID = FKC.PARENT_OBJECT_ID
JOIN SYS.TABLES RT ON RT.OBJECT_ID = FK.referenced_object_id -- REFERENCE TABLE
-- AND RT.OBJECT_ID = FKC.parent_column_id
JOIN SYS.COLUMNS PC ON PC.OBJECT_ID = PT.OBJECT_ID
AND PC.COLUMN_ID = FKC.PARENT_COLUMN_ID
JOIN SYS.COLUMNS RC ON RC.OBJECT_ID = RT.OBJECT_ID
AND RC.COLUMN_ID = FKC.referenced_column_id
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2009-09-28 : 17:05:54
This script will do what you want if the database has foreign keys defined.

Find Table Reference Levels
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72957



CODO ERGO SUM
Go to Top of Page

rohitkumar
Constraint Violating Yak Guru

472 Posts

Posted - 2009-09-28 : 17:25:26
wow, thanks for the script mvj
Go to Top of Page
   

- Advertisement -