数据完整性(Data Integrity)笔记
因数据库存储数据要持之以恒,数据库中的表需要一些方法验证各种数据类型。不仅仅局限于数据类型,还有唯一值,值的范围,或者某列的值和另外一个表中的列匹配。
当你在定义表的时候其用这些数据验证方法。这叫做声明数据完整性。也就是我们说的表约束。
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
参考文章
数据完整性(Data Integrity)笔记的更多相关文章
- [svc]对称加密/非对称加密细枝末节-如何做到数据传输的authentication/data integrity/confidentiality(私密)
对称/非对称/混合加密的冷知识 数据在互联网上传输,要考虑安全性. 讲到安全,要从三方面考虑: 1.authentication 每一个IP包的认证,确保合法源的数据 2.data integrity ...
- SQL Server 第四章 存储过程(Procedure),触发器(Trigger),数据完整性(Data Integrity)
use electric go --变量 --局部变量的声明格式 --declare @局部变量名 数据类型 --局部变量赋值 declare @littlepage int )) ) select ...
- Pentaho Data Integration笔记 (一):安装
介绍 Pentaho Data Integration (PDI) is an extract, transform, and load (ETL) solution that uses an inn ...
- Spring Data JPA笔记
1. Spring Data JPA是什么 Spring Data JPA是Spring Data大家族中的一员,它对对持久层做了简化,用户只需要声明方法的接口,不需要实现该接口,Spring Dat ...
- JQuery中attr属性和jQuery.data()学习笔记
用html直接data-key来存放,key必须全部小写. <div data-mydata="123"></div> consoloe.log($(&qu ...
- [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 ...
- JavaEE高级-Spring Data学习笔记
Spring Data概述 - Spring Data : Spring 的一个子项目.用于简化数据库访问,支持NoSQL 和 关系数据存储.其主要目标是使数据库的访问变得方便快捷. - Spring ...
- Pentaho Data Integration笔记 (四):Kitchen
官方网站: http://wiki.pentaho.com/display/EAI/Kitchen+User+Documentation Kitchen Kitchen是一个可以执行Spoon编辑的J ...
- "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 ...
随机推荐
- python 之日期时间处理
##python时间操作一般使用time.datetime两个模块 对于time模块,时间的表示模式有3种1.时间戳:time.time()2.字符串: time.strftime('%Y%m%d') ...
- Uva 1612 Guess
Thinking about it: 题目要求最后一名(也就是第N位)的分数要尽量的大,那么就一定要求第N-1名的分数也要尽量大.假如N-1可以取400和500,那么N-1应该取500,如果取400, ...
- ZOJ 38727(贪心)
这道题真心坑.越想越远 想的飞起来了. 最后纠结起后缀表达式的定义来了. 题意: 就是给你一个串 , 让你用最少改动次数来实它变成一个合法的后缀表达式, 改动方式有两种, 一种是直接加入数字或者 ...
- Android进程的内存管理分析
尊重原创作者,转载请注明出处: http://blog.csdn.net/gemmem/article/details/8920039 最近在网上看了不少Android内存管理方面的博文,但是文章大多 ...
- 很郁闷,七日筑基C#第二天的内容未保存
很郁闷,七日筑基C#第二天的内容写了好几百字未保存,刚才死机了,一下打击得不行了.
- CXF详细介绍
首先介绍下CXF的拦截器:简单地说,CXF使用流水线型(或者说总线型)处理机制,它的核心是一个Bus.一个客户端的请求或者一个对客户端桩代码的调用被组织成为一个Message.同时,所有的CXF功能都 ...
- BestCoder Round #38
1001 Four Inages Strategy 题意:给定空间的四个点,判断这四个点是否能形成正方形 思路:判断空间上4个点是否形成一个正方形方法有很多,这里给出一种方法,在p2,p3,p4中枚举 ...
- OA项目总结
一.自定义拦截器: 继承AbstractInterceptor,覆写intercept方法,实现功能逻辑,最后在Struts.xml文件中配置了自定义拦截器,首先自定义拦截器栈, <!- ...
- MySQL 事物
BEGIN DECLARE result INTEGER DEFAULT 0; -- 标记是否出错 DECLARE t_error INTEGER DEFAULT 0; -- 如果出现sql异常,则将 ...
- ThinkPHP第二十天(getField用法、常用管理员表结构、树形结构前小图标CSS)
1.getField($fields,$sepa=null) A:当$fields为1个字段,$sepa=null的时候,返回一个符合条件的记录的字段. B:如果要取得所有符合条件记录字段,需要$se ...