How to check foreign key/relationship between tables

M Jugnu 41 Reputation points
2020-10-28T00:39:44.61+00:00

Hi,
I have following Six tables and each table has some relationship with another table. How I can check relationship of these tables from query to know so I can create and join the query with these tables.

Table:
Sales
Marketing
Product
Finance
Profit
Design

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
0 comments No comments
{count} votes

Accepted answer
  1. MelissaMa-MSFT 24,196 Reputation points
    2020-10-28T01:07:28.933+00:00

    Hi @M Jugnu ,

    Please refer below query and check whether it is helpful to you.

    USE DATEBASENAME --YOUR DATABASENAME  
    GO  
    SELECT t.name AS FKTableName  
       , fk.name AS NameOfForeignKey  
       , pc.name AS FKColumn  
       , rt.name AS ReferencedTable  
       , c.name AS ReferencedColumn  
    FROM sys.foreign_key_columns AS fkc  
    INNER JOIN sys.foreign_keys AS fk ON fkc.constraint_object_id = fk.object_id  
    INNER JOIN sys.tables AS t ON fkc.parent_object_id = t.object_id  
    INNER JOIN sys.tables AS rt ON fkc.referenced_object_id = rt.object_id  
    INNER JOIN sys.columns AS pc ON fkc.parent_object_id = pc.object_id  
       AND fkc.parent_column_id = pc.column_id  
    INNER JOIN sys.columns AS c ON fkc.referenced_object_id = c.object_id  
       AND fkc.referenced_column_id = c.column_id  
       where t.name in ('Sales','Marketing''Product','Finance','Profit','Design')  
    

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MelissaMa-MSFT 24,196 Reputation points
    2020-10-28T01:14:31.38+00:00

    Hi @M Jugnu ,

    You could also refer below forum for more queries about how to list all foreign keys referencing a given table in SQL Server which could be helpful to you.
    How can I list all foreign keys referencing a given table in SQL Server?

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.