What is Foreign key and how to create a Foreign key constraint?

Note:Foreign
Keys are used to enforce(强制) database integrity(完整) . In layman's
terms(一般来说), A foreign key in one table points to a primary key in
another table. The foreign key constraint prevents invalid data form
being inserted into the foreign key column. The values that you enter
into the foreign key column, has to be one of the values contained in
the table it points to.

for example:add a foreign key relation.

Table - Student: ID, GenderID;

Gender: ID, StudentID;

alter table Student add constraint FK_Student_GenderID
foreign key (GenderID) references Gender (ID) Syntax:
ALTER TABLE 外键表名 ADD CONSTRAINT 外键约束名
FOREIGN KEY (外键名) REFERENCES 主表名 (主键名)

Adding a default constraint and dropping a constraint

Altering an existing column to add a default constraint:

alter table Gender
add constraint DF_Gender_ID
default 1 for ID Syntax:
ALTER TABLE 表名
ADD CONSTRAINT 约束名
DEFAULT 默认值 FOR 列名

Adding a new column with default value, to an existing table:

alter table Student
add Name nvarchar(20) not null
constraint DF_Student_Name default 'gester' Syntax:
ALTER TABLE 表名
ADD 列名 数据类型 是否允许null
CONSTRAINT 约束名 DEFAULT 默认值

Dropping a constraint:

alter table Student
drop constraint DF_Student_Name Syntax:
ALTER TABLE 表名
DROP CONSTRAINT 约束名

Cascading referential integrity constraint

Cascading referential integrity constraint allows to define the actions Microsoft SQL Server should take when a user attempts to delete or update a key to which an existing foreign keys points.

For example, consider the 2 tables shown below. If you delete row with ID = 1 fromtblGender table, then row with ID = 3 from tblPerson table becomes an orphan record. You will not be able to tell the Gender for this row. So, Cascading referential integrity constraint can be used to define actions Microsoft SQL Server should take when this happens. By default, we get an error and the DELETE or UPDATE statement is rolled back. 

 

However, you have the following options when setting up Cascading referential integrity constraint

1. No Action: This is the default behaviour. No Action specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE or UPDATE is rolled back.

2. Cascade: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are also deleted or updated.

3. Set NULL: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to NULL.

4. Set Default: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to default values.

Adding a check constraint

CHECK constraint is used to limit the range of the values, that can be entered for a column.

Let's say, we have an integer AGE column, in a table. The AGE in general cannot be less than ZERO and at the same time cannot be greater than 150. But, since AGE is an integer column it can accept negative values and values much greater than 150.

So, to limit the values, that can be added, we can use CHECK constraint. In SQL Server, CHECK constraint can be created graphically, or using a query.

The following check constraint, limits the age between ZERO and 150.
ALTER TABLE tblPerson
ADD CONSTRAINT CK_tblPerson_Age CHECK (Age > 0 AND Age < 150)

The general formula for adding check constraint in SQL Server:
ALTER TABLE { TABLE_NAME }
ADD CONSTRAINT { CONSTRAINT_NAME } CHECK ( BOOLEAN_EXPRESSION )

If the BOOLEAN_EXPRESSION returns true, then the CHECK constraint allows the value, otherwise it doesn't. Since, AGE is a nullable column, it's possible to pass null for this column, when inserting a row. When you pass NULL for the AGE column, the boolean expression evaluates to UNKNOWN, and allows the value.

To drop the CHECK constraint:
ALTER TABLE tblPerson
DROP CONSTRAINT CK_tblPerson_Age

Unique key constraint

We use UNIQUE constraint to enforce uniqueness of a column i.e the column shouldn't allow any duplicate values. We can add a Unique constraint thru the designer or using a query.
To add a unique constraint using SQL server management studio designer:
1. Right-click on the table and select Design
2. Right-click on the column, and select Indexes/Keys...
3. Click Add
4. For Columns, select the column name you want to be unique.
5. For Type, choose Unique Key.
6. Click Close, Save the table.

To create the unique key using a query:

Alter Table Table_Name
Add Constraint Constraint_Name Unique(Column_Name)

Both primary key and unique key are used to enforce, the uniqueness of a column. So, when do you choose one over the other?
A table can have, only one primary key. If you want to enforce(强制) uniqueness on 2 or more columns, then we use unique key constraint.

What is the difference between Primary key constraint and Unique key constraint? This question is asked very frequently in interviews.
1. A table can have only one primary key, but more than one unique key
2. Primary key does not allow nulls, where as unique key allows one null

To drop the constraint
1. Right click the constraint and delete.
Or
2. Using a query

Alter Table tblPerson
Drop COnstraint UQ_tblPerson_Email

Part 3 talking about constraint in sql的更多相关文章

  1. SQL基础--&gt; 约束(CONSTRAINT)

    --============================= --SQL基础--> 约束(CONSTRAINT) --============================= 一.几类数据完 ...

  2. SQL Server - 约束 CONSTRAINT

    总结 约束放置在表中,以下五种约束: NOT NULL 非空约束C 指定的列不允许为空值 UNIQUE 唯一约束U 指定的列中没有重复值,或该表中每一个值或者每一组值都将是唯一的 PRIMARY KE ...

  3. Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one SQL statement

    Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and d ...

  4. SQL PRIMARY KEY 约束\SQL FOREIGN KEY 约束\SQL CHECK 约束

    SQL PRIMARY KEY 约束 PRIMARY KEY 约束唯一标识数据库表中的每条记录. 主键必须包含唯一的值. 主键列不能包含 NULL 值. 每个表都应该有一个主键,并且每个表只能有一个主 ...

  5. SQL语句删除所有表

    ) )     ) )     ) )     ) ) )  TABLE_NAME  CONSTRAINT_NAME  CONSTRAINT_NAME  TABLE_NAME ) ) )  TABLE ...

  6. Oracle导出的sql执行出错

    建的表如果有constraint的话sql语句中会有create unique index...而在前面的建表语句中,这个index实际上已经建好了. 所以导出的sql语句,应该将后面的create ...

  7. SQL SERVER 中的 object_id()函数

    在SQLServer数据库中,如果查询数据库中是否存在指定名称的索引或者外键约束等,经常会用到object_id('name','type')方法,做笔记如下: ? 语法:object_id('obj ...

  8. SQL[连载3]sql的一些高级用法

    SQL[连载3]sql的一些高级用法 SQL 高级教程 SQL SELECT TOP SQL SELECT TOP 子句 SELECT TOP 子句用于规定要返回的记录的数目. SELECT TOP ...

  9. [SQL Server系] -- 约束

    什么是约束? 约束(Constraint)是SQL Server中提供的 自动保存数据库完整性 的一种方法,定义了可输入表或表的列中的数据限制条件. SQL Server中共有5中约束 PRIMARY ...

随机推荐

  1. c# 使用hook来监控鼠标键盘事件的示例代码

    如果这个程序在10几年前,QQ刚刚兴起的时候,有了这个代码,就可实现盗号了. 当然使用钩子我们更多的是实现"全局快捷键"的需求. 比如 程序最小化隐藏后要"某快捷键&qu ...

  2. SQL with(unlock)与with(readpast) (转)

    所有Select加 With (NoLock)解决阻塞死锁,在查询语句中使用 NOLOCK 和 READPAST 处理一个数据库死锁的异常时候,其中一个建议就是使用 NOLOCK 或者 READPAS ...

  3. 浅析C#基于TCP协议的SCOKET通信

    TCP协议是一个基本的网络协议,基本上所有的网络服务都是基于TCP协议的,如HTTP,FTP等等,所以要了解网络编程就必须了解基于TCP协议的编程.然而TCP协议是一个庞杂的体系,要彻底的弄清楚它的实 ...

  4. hdu 4828 Grids(拓展欧几里得+卡特兰数)

    题目链接:hdu 4828 Grids 题目大意:略. 解题思路:将上一行看成是入栈,下一行看成是出栈,那么执着的方案就是卡特兰数,用递推的方式求解. #include <cstdio> ...

  5. android百度地图开发之自动定位所在位置与固定位置进行驾车,步行,公交路线搜索

    最近跟着百度地图API学地图开发,先是学了路径搜索,对于已知坐标的两点进行驾车.公交.步行三种路径的搜索(公交路径运行没效果,待学习中),后来又 学了定位功能,能够获取到自己所在位置的经纬度,但当将两 ...

  6. 无需图片,使用CSS3实现圆角按钮[转]

    首先来看看效果:   事例HTML代码: <a href="#" class="button green">button</a> < ...

  7. Preventing CSRF in Java web apps---reference

    reference from:http://ricardozuasti.com/2012/preventing-csrf-in-java-web-apps/ Cross-site request fo ...

  8. 关于子线程使用Toast报错Can't create handler inside thread that has not called Looper.prepare()的解决办法

    形同如下代码,在Thread中调用Toast显示错误信息: new Thread(new Runnable(){ @Override public void run() { try{ weatherD ...

  9. .net 后台获取当前请求的设备

    检查当前发起请求的设备是手持设备还是电脑端  以便显示不同的视图 public static bool CheckIsMobile(HttpRequestBase req) { bool flag = ...

  10. Fliptile 开关问题 poj 3279

    Fliptile Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 4031   Accepted: 1539 Descript ...