In this article, we will create tblStudent and tblCourse tables and set up Primary Key and Foreign Key constraints. In SQL Server, We can create tables and set Primary and Foreign Key using given two ways:-


1. Graphically using SQL Server Management Studio (SSMS)
2. Using T-SQL.

(1). Follow the given steps to create tables tblStudent and tblCourse and set Primary Key graphically using SQL Server Management Studio (SSMS) 

(i). Right-click on the Table Folder and then select the table option as shown below from the list


    (ii). Enter the Column Name, Data Type, check/uncheck Allow Nulls and set SRNo as Primary Key as shown below and save the table as tblStudent


    (iii). In the same way, create the table tblCourse



    (2). Use the given query to create tables tblStudent and tblCourse with Primary Key Using T-SQL.

    (i) Use the below query to creae table tblStudent.

     
      CREATE TABLE TblStudent
         (
                SRNo VARCHAR(15) NOT NULL PRIMARY KEY,
                StudentName VARCHAR(50),
                FatherName VARCHAR(50),
                CourseCode VARCHAR(15)
         )

    (ii) Use the below query to create table tblCourse

      CREATE TABLE TblCourse
         (
                CourseCode VARCHAR(15) NOT NULL PRIMARY KEY,
             CourseName VARCHAR(50)
         )

    In the tblStudent table, CourseCode is the foreign key that referencing CourseCode column in the tblCourse table. We can add Foreign key references graphically using SSMS or using a T-SQL.

     

    (1). Use the below steps to add Foreign key references graphically using SSMS.

    1. Right-click on tblStudent table and select the Design option 


    2. In the table design window, right-click on CourseCode column and select Relationships


    3. In the Foreign Key Relationships window, click Add button

    4. Click on '…' icon as yellow-highlighted in the given screenshot of  'Table and Columns Specification'

     


    5. (i) As CourseCode is Primary Key in tblCourse table so select tblCourse as 'Primary Key Table' and 'CourseCode' column as 'Primary Key table' column.
    (ii) As CourseCode behave as Foreign Key for tblStudent table so select tblStudent as 'Foreign Key Table and Select 'CourseCode' column as 'Foreign Key table' column and then click OK.


    (2). Use the given query to add Foreign Key using T-SQL

    Alter table tblStudent add constraint tblStudent_CourseCode_FK FOREIGN KEY (CourseCode) references tblCourse(CourseCode)