Activate foreign keys in SQL Server

This article explains how to enable a foreign key created in SQL Server.

When the FOREIGN KEY foreign key in SQL Server has been disabled, you can enable / re-enable with the ALTER TABLE command.

The syntax for activating foreign keys in SQL Server

 ALTER TABLE ten_bang 
CHECK CONSTRAINT fk_ten;

Variable name or variable value

ten_bang

The name of the table to which the foreign key has been created.

fk_ten

The name of the foreign key you want to disable.

For example

 CREATE T ABLE sanpham 
( id_sanpham INT PRIMARY KEY,
ten_sanpham VARCHAR(50) NOT NULL,
phan_loai VARCHAR(25)
);

CREATE TABLE hangtonkho
( id_hangtonkho INT PRIMARY KEY,
id_sanpham INT NOT NULL,
soluong INT,
luong_toithieu INT,
luong_toida INT,
CONSTRAINT fk_htk_id_sanpham
FOREIGN KEY (id_sanpham)
REFERENCES sanpham (id_sanpham)
);

In this example, we created the parent table, sanpham, with the primary key including the information field id_sanpham. Then there is a child table named hangtonkho with a foreign key with deletion constraint. The CREATE TABLE statement creates a foreign key on the hangtonkho table named fk_htk_id_sanpham. The foreign key forms the relationship between the id_sanpham column in the hangtonkho table and id_sanpham in the sanpham table.

  1. Foreign Key (Cascade Delete) in SQL Server
  2. Foreign Key (Set Null) foreign key in SQL Server

If you want to re-enable the foreign key, run the following command.

 ALTER TABLE hangtonk ho 
CHECK CONSTRAINT fk _htk_id_sanpham;

The example above uses the ALTER TABLE command to re-enable the foreign key named fk_htk_id_sanpham in the hangtonkho table.

Previous article: Disable foreign key in SQL Server

The following article: Unique binding in SQL Server

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile