Setting Primary and Foreign Keys while table creation using T-SQL Statements

Self-Innovator
Posted by Self-Innovator under Sql Server category on | Points: 40 | Views : 1242
Dear Users the below is a code snippet for creating a primary and foreign keys for tables in SQL Server in different ways
Primary Key
Method 1
CREATE TABLE CourseMaster
(
ID INT IDENTITY(1,1) CONSTRAINT pk_Coursemaster PRIMARY KEY,
COURSENAME VARCHAR(40) NOT NULL
)

Method 2
CREATE TABLE CourseMaster
(
ID INT IDENTITY(1,1),
COURSENAME VARCHAR(40) NOT NULL
CONSTRAINT pk_Coursemaster PRIMARY KEY(ID)
)


FOREIGN KEY
CREATE TABLE Courses
(
ID INT IDENTITY(1,1) CONSTRAINT pk_Coursesid PRIMARY KEY,
COURSEID INT CONSTRAINT fk_Courseid FOREIGN KEY REFERENCES CourseMaster(ID),
COURSENAME VARCHAR(40) NOT NULL
)


DROPPING FOREIGN KEY CONSTRAINTS
ALTER TABLE Courses DROP constraint fk_Courseid


ADDING FOREIGN KEYS USING ALTER STATEMENT
ALTER TABLE COURSES ADD CONSTRAINT fk_CourseID FOREIGN KEY (COURSEID)  REFERENCES COURSEMASTER(ID)

Comments or Responses

Login to post response