0

I am working with SQL Server 2012. I have a table. I am looking for tables which are referring to this table.

e.g. TestTable.

Now there are two tables:

  1. ChildTable1
  2. ChildTable2

How to find that these two tables have relationship with TestTable?

Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
unknown
  • 4,859
  • 10
  • 44
  • 62
  • 2
    Check this out: http://stackoverflow.com/questions/925738/how-to-find-foreign-key-dependencies-in-sql-server – Tom Chantler Dec 09 '14 at 08:35
  • 1
    or this: http://stackoverflow.com/questions/483193/how-can-i-list-all-foreign-keys-referencing-a-given-table-in-sql-server – Scherling Dec 09 '14 at 08:38
  • 1
    http://stackoverflow.com/questions/11866081/mssql-how-to-i-find-all-tables-that-have-foreign-keys-that-reference-particular – Deepak Mishra Dec 09 '14 at 08:38

3 Answers3

1

You can use the following query

select 
   object_name(f.parent_object_id) tname,
   col_name(fc.parent_object_id,fc.parent_column_id) cname
from  sys.foreign_keys as f
    join sys.foreign_key_columns as fc on f.object_id = fc.constraint_object_id
    join sys.tables t on t.object_id = fc.referenced_object_id
WHERE  OBJECT_NAME (f.referenced_object_id) = 'AspNetUsers'

Where AspNetUsers is your master table

fly_ua
  • 1,034
  • 8
  • 12
1

This would be the shortest query to retrieve your information.

EXEC sp_fkeys 'TableName'
0

This is what I was looking for. It lists all Foreign Key Relationships within the current database.

SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_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

You can also view relationships graphically within SQL Server Management studio within Database Diagrams.

unknown
  • 4,859
  • 10
  • 44
  • 62