因数据库存储数据要持之以恒,数据库中的表需要一些方法验证各种数据类型。不仅仅局限于数据类型,还有唯一值,值的范围,或者某列的值和另外一个表中的列匹配。

当你在定义表的时候其用这些数据验证方法。这叫做声明数据完整性。也就是我们说的表约束。

USE tempdb
GO
CREATE TABLE s
(
sid VARCHAR(20) ,
sname VARCHAR(20) ,
ssex VARCHAR(2) CHECK ( ssex = '男'
OR ssex = '女' )
DEFAULT '男' ,
sage INT CHECK ( sage BETWEEN 0 AND 100 ) ,
sclass VARCHAR(20) UNIQUE ,
CONSTRAINT PK_s PRIMARY KEY ( sid, sclass )
)
CREATE TABLE t
(
teacher VARCHAR(20) PRIMARY KEY ,
sid VARCHAR(20) NOT NULL ,
sclass VARCHAR(20) NOT NULL ,
num INT ,
FOREIGN KEY ( sid, sclass ) REFERENCES s ( sid, sclass )
)

主键约束 Primary Key Constraints

primary key = unique constraint + not null constraint

创建主键约束时,数据库自动创建唯一索引,默认为聚集索引

创建方法一

-- Primary Key Constraints
CREATE TABLE Production.Categories
(
categoryid INT NOT NULL IDENTITY,
categoryname NVARCHAR(15) NOT NULL,
description NVARCHAR(200) NOT NULL,
CONSTRAINT PK_Categories PRIMARY KEY(categoryid)
);

创建方法二

USE TSQL2012;
ALTER TABLE Production.Categories
ADD CONSTRAINT PK_Categories PRIMARY KEY(categoryid);
GO

列出数据库中的主键约束

-- To list the primary key constraints in a database, you can query the sys.key_constraints table filtering on a type of PK:
SELECT *
FROM sys.key_constraints
WHERE type = 'PK';

唯一性约束 Unique Constraints

仅可以有一行为NULL,ORACLE中可以有多行列值为NULL。

创建唯一键约束时,数据库自动创建唯一索引,默认为非聚集索引

在保证数据唯一性上,唯一索引、唯一约束并没有区别,那么应该使用约束还是索引?

约束定义通常出现在数据库逻辑结构设计阶段,即定义表结构时,索引定义通常出现在数据库物理结构设计/查询优化阶段。

从功能上来说唯一约束和唯一索引没有区别,但在数据库维护上则不太一样,对于唯一约束可以用唯一索引代替,以方便维护,但是主键约束则没法代替。

ALTER TABLE Production.Categories
ADD CONSTRAINT UC_Categories UNIQUE (categoryname);
GO

列出数据库中的唯一约束

SELECT *
FROM sys.key_constraints
WHERE type = 'UQ';

外键 Foreign Key Constraints

创建

ALTER TABLE Production.[Products]  WITH CHECK
ADD CONSTRAINT [FK_Products_Categories] FOREIGN KEY(categoryid)
REFERENCES Production.Categories (categoryid)

查找外键

SELECT *
FROM sys.foreign_keys
WHERE name = 'FK_Products_Categories';

删除外键

ALTER TABLE Production.Products DROP CONSTRAINT FK_Products_Categories;

检查约束 Check Constraints

创建

ALTER TABLE Production.Products WITH CHECK
ADD CONSTRAINT CHK_Products_unitprice
CHECK (unitprice>=0);
GO
ALTER TABLE dbo.NewTable
ADD ZipCode INT NULL
CONSTRAINT CHK_ZipCode
CHECK (ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]');

查找检查约束

SELECT *
FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID(N'Production.Products', N'U');

默认约束 Default Constraints

创建

CREATE TABLE Production.Products
(
productid INT NOT NULL IDENTITY,
productname NVARCHAR(40) NOT NULL,
supplierid INT NOT NULL,
categoryid INT NOT NULL,
unitprice MONEY NOT NULL
CONSTRAINT DFT_Products_unitprice DEFAULT(0),
discontinued BIT NOT NULL
CONSTRAINT DFT_Products_discontinued DEFAULT(0),
);

查找

SELECT *
FROM sys.default_constraints
WHERE parent_object_id = OBJECT_ID(N'Production.Products', 'U');

启用和禁用约束检查

ALTER TABLE Products NOCHECK CONSTRAINT CHK_Price;
ALTER TABLE Products CHECK CONSTRAINT CHK_Price;

检查在SQL Server中的约束

--Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function...
IF OBJECT_ID('CK_ConstraintName', 'C') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
--OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results.
IF OBJECT_ID('CK_ConstraintName') IS NOT NULL
ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
--OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:
--Constraint Object Types:
--•C = CHECK constraint
--•D = DEFAULT (constraint or stand-alone)
--•F = FOREIGN KEY constraint
--•PK = PRIMARY KEY constraint
--•R = Rule (old-style, stand-alone)
--•UQ = UNIQUE constraint

参考文章

09. 约束与索引的联系

数据完整性(Data Integrity)笔记的更多相关文章

  1. [svc]对称加密/非对称加密细枝末节-如何做到数据传输的authentication/data integrity/confidentiality(私密)

    对称/非对称/混合加密的冷知识 数据在互联网上传输,要考虑安全性. 讲到安全,要从三方面考虑: 1.authentication 每一个IP包的认证,确保合法源的数据 2.data integrity ...

  2. SQL Server 第四章 存储过程(Procedure),触发器(Trigger),数据完整性(Data Integrity)

    use electric go --变量 --局部变量的声明格式 --declare @局部变量名 数据类型 --局部变量赋值 declare @littlepage int )) ) select ...

  3. Pentaho Data Integration笔记 (一):安装

    介绍 Pentaho Data Integration (PDI) is an extract, transform, and load (ETL) solution that uses an inn ...

  4. Spring Data JPA笔记

    1. Spring Data JPA是什么 Spring Data JPA是Spring Data大家族中的一员,它对对持久层做了简化,用户只需要声明方法的接口,不需要实现该接口,Spring Dat ...

  5. JQuery中attr属性和jQuery.data()学习笔记

    用html直接data-key来存放,key必须全部小写. <div data-mydata="123"></div> consoloe.log($(&qu ...

  6. [PostgreSQL] Use Foreign Keys to Ensure Data Integrity in Postgres

    Every movie needs a director and every rented movie needs to exist in the store. How do we make sure ...

  7. JavaEE高级-Spring Data学习笔记

    Spring Data概述 - Spring Data : Spring 的一个子项目.用于简化数据库访问,支持NoSQL 和 关系数据存储.其主要目标是使数据库的访问变得方便快捷. - Spring ...

  8. Pentaho Data Integration笔记 (四):Kitchen

    官方网站: http://wiki.pentaho.com/display/EAI/Kitchen+User+Documentation Kitchen Kitchen是一个可以执行Spoon编辑的J ...

  9. "Error 0162 - Setup data integrity check failure" after updating BIOS via Thinkvantage

    Start the computer and start pressing F1 and get into set up. In setup press F9 for default settings ...

随机推荐

  1. java反编译命令javap

    1. 输出所有类和成员 javap -private XX.class 2. 输出分解后的代码 javap -c XX.class

  2. MySQLD 配置

    http://blog.163.com/sir_876/blog/static/11705223201372710303382/ http://www.kankanews.com/ICkengine/ ...

  3. QT完美转换特殊字符的大小写

    Util::ShowMessage(QString::fromUtf8("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØŒŠþÙÚÛÜÝŸ€")); Util::ShowMess ...

  4. zookeeper 伪集群模式

    问题二:开发没有足够机器,一台机子上是否装三个zookeeper服务器集群. 问题解答: 这种安装模式只能说是一种伪集群模式.三个zookeeper服务器都安装在同一个服务器(platform)上,需 ...

  5. C++读写EXCEL文件OLE,java读写excel文件POI 对比

    C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ...

  6. Android系统JNI的实现方式

     Android系统JNI的实现方式 All rights reserved JNI(Java Native Interface)定义了一种Java代码调用C或者C++代码等其它代码的方式. 在A ...

  7. TabelView的多选模式

    @interface ViewController ()<UITableViewDelegate,UITableViewDataSource> @property(nonatomic,st ...

  8. HOOK API(四)—— 进程防终止

    HOOK API(四) —— 进程防终止 0x00        前言 这算是一个实战吧,做的一个应用需要实现进程的防终止保护,查了相关资料后决定用HOOK API的方式实现.起初学习HOOK API ...

  9. JAVA 对象内存分析

    1.jmap -heap pid 或者 jmap -histo pid 2.jmap -dump:file=folder/dumpFileName.txt,format=b pid 3.对3的输出文件 ...

  10. canvas绘制弹跳小球

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...