怎么添加外键约束

怎么添加外键约束,第1张

sql server中建立外键约束有3中方式: 1Enterprise Manager中,Tables,Design Table,设置Table的properties, 可以建立constraint, reference key; 2Enterprise 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

参考资料:

>

要你数据库设计合理,使用合法,可以不需要外键

1

外键是将b表的某列和a表的主键连接起来。

a的主键是id,那么就是它了。

2

select

ausername,auserpwd,bgold

from

a,b

where

aid=bgold;

3

同时更新或者 *** 作两个表(比如通过a的值来检索b的值)?

通过a的值来检索b的值

就如上面所说一个sql语句就可以了。

同时更新的话你可以用触发器。也可以用存储过程。

在存储过程中直接对两个表进行 *** 作就能达到你的目的。

你的问题还很笼统。如果不明白最好就一个具体问题来提问。

以上就是关于怎么添加外键约束全部的内容,包括:怎么添加外键约束、如何修改数据库中主外键约束的数据、数据库该不该用外键等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9416369.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-28
下一篇2023-04-28

发表评论

登录后才能评论

评论列表(0条)

    保存