当前位置: 代码迷 >> Sql Server >> 建表时,如何让一个列的取值必须在另一个列所有取值范围内
  详细解决方案

建表时,如何让一个列的取值必须在另一个列所有取值范围内

热度:53   发布时间:2016-04-24 10:49:48.0
建表时,怎么让一个列的取值必须在另一个列所有取值范围内?
rt,比如说我想建一个课程表,有列课程ID,课程名称,先行课。那么我要约束先行课必须在课程ID里取值。。。
------解决方案--------------------
加个check约束

------解决方案--------------------
create table tb
(id int not null,
name varchar(10) not null,
pid int null,
constraint PK_tb primary key nonclustered (id)
)
go
alter table tb
   add constraint FK_self foreign key (pid)
      references tb (id)
go
alter table tb
add constraint CHK_tb CHECK(pid<>id)
  相关解决方案