Foreign Key Constraints – SSMS

Background

Having restored Stack Overflow’s Database version 2008-2010, reviewing the tables and their relationships.

BTW, that post is here.

 

Database Diagram

DBeaver

Original

Image

 

Explanation

  1. No Relationship

 

Create Foreign Key

SSMS

Objective

Let us relate the dbo.Badges table to the dbo.Users table.

The correlating columns are dbo.Badges.UserId and dbo.Users.Id.

Outline

  1. Launch SSMS
  2. Connect to the SQL Server Instance
  3. Choose the database
  4. Select the table that will we will be targeting
    • Access the Keys node
    • Right click on the Keys Node
    • From the drop-down menu, Select “new Foreign-Key…” option
  5. “Foreign Key relationships” window
    • The “Foreign Key relationships” window appears
    • Group Area :- Tables and Column specifications
      • Please zero in on “Tables and Column specifications” group area
      • Click the eclipse ( “…”) button
  6. Tables and Column Window
    • The “Table and Column” window appears
    • Both sides ( Primary and Foreign Key ) show our targeted table
    • Primary
      • Please adjust our primary, the left side as stated below
        • Table Name
          • Users
        • Column Names
          • Id
  7. Exit Designer Window
    • Please press OK as many times as possible to exit the table designer windows
  8. Generate Change Script
    • Please access the menu items ( Table Designer, Generate Change Script )
  9. Save Change Script
    • The “Save Change Script” window appears
  10. Review Generated Script

Images

New Foreign Key

Foreign Key relationships
Display – Original

The original window shows a self relationship, the Badges table related to the Badges table.

 

Tables and Columns
Display – Original

Display – Revised

We want to state that our targeted table is dbo.Badges and the referenced table is dbo.Users.

The columns that participate from the Badges table is UserId.  And, the Id column in the Users table.

Foreign Key Relationships
Display – Revised

Generate Change Script
Save Change Script

 

Database Diagram

Microsoft

SSMS

Image

databaseDiagram_20180719_0453PM

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s