Six kinds of constraints SQL Server

In SQL Server constraints (six kinds of constraints)

First, what are the constraints?

Database - composed by a number of data tables (understood as a class library), the data table - a two-dimensional array of rows and columns (understood as a category), column - field (understood as a property of the object table), OK - is understood as an object table, a database constraint is to ensure the integrity of the data

1.1. Entity integrity

Each table has a field must be specified

1.2 Regional Integrity

Be restrictions on specialization in a field in the table

1.3. Referential integrity

One kind of specialization restricted association between the table and the table

Second, the constraint type (six kinds):

Constraint Type Explanation
Primary key constraint (PRIMARY KEY) Identity column (primary key can not be empty, must be unique) identifier determination table: determining a target performance unique
Foreign key constraint (FOREIGN KEY) Contact between the table and the table is determined, generally determined by the primary table identifies the column of the primary table: add a constraint to which tables tables which is the primary table, the secondary table from the table
The only constraint (UNIQUE) Determine the data in this field must be unique existence
Non-empty constraint (NOT NULL) Determine the data in this field must not be empty
Check constraints (CHECK) This set of data characteristics field
Default constraint (DEFAULT) If the constraint defines the default value in the table, users insert new rows of data, if the data line is not specified, the system will default value is assigned to the column, if we do not set a default value, the system defaults to NULL.

2.1. Primary key constraint (PRIMARY KEY)

ALTER TABLE 数据表名
ADD CONSTRAINT PK_ID        --(命名一个主键名称)
PRIMARY KEY(ID)

2.2 foreign key constraints (FOREIGN KEY)

ALTER TABLE 从表名称
ADD CONSTRAINT FK_SID        --(命名一个外键名称)
--添加外键约束
FOREIGN KEY(StuID) REFERENCES 主表名称(ID)

2.3. The only constraint (UNIQUE)

ALTER TABLE 数据表名称
ADD CONSTRAINT QU_Name        --(命名一个唯一约束的名称)
UNIQUE([Name])

2.4. Non-empty constraint (NOT NULL)

ALTER TABLE 数据表名称
ALTER COLUMN ID INT NOT NULL

2.5 Check constraints (the CHECK)

ALTER TABLE 数据表名称
ADD CONSTRAINT CK_SEX                --(命名一个检查约束的名称)
CHECK(SEX IN('男','女'));

2.6. The default constraint (DEFAULT)

2.6.1 If the table field has been built

--DF_XXX(命名一个默认约束的名称)
ALTER TABLE 表名 
ADD CONSTRAINT DF_XXX  DEFAULT 1 FOR 字段名

2.6.2 If the table field is not completed

2. 如果表字段没有建
ALTER 表名 ADD 字段名 INT DEFAULT(1)

2.6.3 Removing Constraints

--删除检查约束
ALTER TABLE 数据表名称
DROP CONSTRAINT CK_AGE--(你想要删除的某个键名或者约束名称)
Published 118 original articles · won praise 225 · views 10000 +

Guess you like

Origin blog.csdn.net/chonbi/article/details/104825060