我们使用sql server创建数据表的时候,经常需要建立表之间的外键约束关系,那么如何添加外键呢?下面我给大家分享一下。
工具/材料sql server
01首先我们先来建立两个表,如下图所示,班级表和年级表
02然后右键单击班级表,在d出的菜单中选择关系选项,如下图所示
03接下来在d出的表和关系界面中设置外键对应字段,如下图所示
04最后我们就可以在左侧看见外键约束关系了,如下图所示
添加外键 ,alter table B
语法:alter table 表名 add constraint 外键约束名 foreign key(列名) references 引用外键表(列名)
如:
alter table Stu_PkFk_Sc
add constraint Fk_s
foreign key (sno)
references Stu_PkFk_S(sno)
--cc是外键约束名,不能重复,也不能是int类型(如1,2,3)
add constraint cc
--B表里的需要约束的字段(id)
foreign key (id)
--A表后的(id)可省略
references A (id)
扩展资料:
数据查询语言,其语句,也称为“数据检索语句”,用以从表中获得数据,确定数据怎样在应用程序给出。保留字SELECT是DQL(也是所有SQL)用得最多的动词,其他DQL常用的保留字有WHERE,ORDER BY,GROUP BY和HAVING。这些DQL保留字常与其他类型的SQL语句一起使用。
参考资料:结构化查询语言_百度百科sql server中建立外键约束有3中方式:1.Enterprise Manager中,Tables,Design Table,设置Table的properties,
可以建立constraint, reference key
2.Enterprise Manager中,Diagrams, new Diagrams,建立两个表的关系。
3.直接用transact sql语句。
下面讲解一下用SQL添加外键约束的实例:
一个SQL创建外键的例子:
/**//*建库,名为student_info*/
create database student_info
/**//*使用student_info*/
use student_info
go
/**//*建student表,其中s_id为主键*/
create table student
(
s_id int identity(1,1) primary key,
s_name varchar(20) not null,
s_age int
)
go
/**//*建test表,其中test_no为主键*/
create table test
(
test_no int identity(1,1) primary key,
test_name varchar(30),
nax_marks int not null default(0),
min_marks int not null default(0)
)
go
/**//*建marks表,其中s_id和test_no为外建,分别映射student表中的s_id和test表中的test_no*/
create table marks
(
s_id int not null,
test_no int not null,
marks int not null default(0),
primary key(s_id,test_no),
foreign key(s_id) references student(s_id),
foreign key(test_no) references test(test_no)
)
go
参考资料: http://www.studyofnet.com/news/93.html
希望以上的回答能够帮到你!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)