如何在sql server数据库中建立主从表

或者如何在两个表中建立关联

建立关联是通过外键引用实现的
例如建立一个学生表和班级表的关联,可以如下:
create table class
(
classid char(4) primary key not null,
classname varchar(10) not null
)
go
create table student
(
stuid char(6) primary key not null,
sname varchar(10) not null,
classid char(4) constraint fk_classid foreign key references class(classid)
)
嫌麻烦的话也可以使用SQL SERVER管理工具中的数据库关系图功能,只需要在关联的表间字段拖拽鼠标就可以了.
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-05
T-SQL代码:
Alter Table 从表名
Add Constraint 约束名 Foreign Key(从表列名) References 主表名(主表列名)本回答被网友采纳
相似回答