日期:2014-05-16  浏览次数:20422 次

创建表约束的语法

一.创建表约束语法:

ALTER TABLE table_name  ADD CONSTRAINT constraint_name constraint_type constraint_definition

?说明:
???????? table_name 要修改的表的名称
???????? constraint_name 约束的名称
???????? constraint_type 约束的类型,有以下四种:?
??????? ???????? PRIMARY KEY 主键约束?
???????????????? FOREIGN KEY 外键约束?
???????????????? CHECK?????? 检查约束?
???????????????? UNIQUE????? 唯一约束
??????? constraint_defintion 约束的定义,不同的约束种类约束的定义是不一样的,每种约束的定义如下:?
???????????????? PRIMARY KEY (field_list)?
???????????????? FOREIGN KEY (source_field_name) REFERENCES target_table(target_field_name)?
???????????????? CHECK (condition)?
???????????????? UNIQUE (field_name)
?例如:
???????? 1. 将Topic表的Id字段修改为主键

ALTER TABLE Topic  ADD CONSTRAINT PK_Topic PRIMARY KEY (Id)

???????? 2. Reply表的TopicId字段引用Topic表的Id字段

ALTER TABLE Reply  ADD CONSTRAINT FK_Reply_Topic FOREIGN KEY (TopicId) REFERENCES Topic(Id)

???????? 3. Student表的Sex字段必须填写“男”或“女”

ALTER TABLE Student  ADD CONSTRAINT CHK_Sex CHECK(Sex='男' OR Sex='女')

?

二.删除表约束语法:

ALTER TABLE table_name  DROP CONSTRAINT constraint_name