sql用命令创建主键与外键,怎么 *** 作?

sql用命令创建主键与外键,怎么 *** 作?,第1张

用命创建主键与外键方法如下:

--用命令创建主键与外键. 

--使用SQL语句创建主键约束可以在创建表(CreateTable)或修改表(AlterTable)时进行 创建。

--例创建表时

createtabletablename

(

idint(CONSTRAINTpk_id)PRIMARYKEY

)

--例修改表时

ALTERTABLEtablename  --修改表

ADD

CONSTRAINTtb_PRIMARY

PRIMARYKEYCLUSTERED(列名)/*将你要设置为主键约束的列*/

sql server中建立外键约束有3中方式:enterprise manager中,tables,design table,设置table的properties,可以建立constraint, reference keyenterprise manager中,diagrams, new diagrams,建立两个表的关系;直接用transact sql语句。

1、三个方法都需要先建立数据表。

1)创建表author :

create table [dbo].[author] (

[id] [bigint] not null ,

[authorname] [char] (10) null ,

[address] [char] (480)  null ,

[introduction] [ntext]  null

)

2)创建表mybbs:

reate table [dbo].[mybbs] (

[id] [bigint] identity (1, 1) not null ,

[authorid] [bigint] not null ,

[title] [char] (40)  null ,

[date_of_created] [datetime] null ,

[abstract] [char] (480)  null ,

[content] [ntext]  null

)

2、设置表mybbs中的authorid为外键,参照author表的id字段,直接使用transact sql语句,过程如下:

1)增加表mybbs(authorid)的外键约束fk_mybbs_author,表mybbs中的authorid受表author中的主键id约束:

begin transaction

alter table dbo.mybbs add constraint fk_mybbs_author

foreign key (authorid)

references  dbo.author([id]) on update cascade on delete cascade

2)删除外键约束fk_mybbs_author:

--alter table dbo.mybbs drop constraint fk_mybbs_author

--rollback

commit transaction

上面on update cascade,on delete cascade两个选项,指明以后author表的id字段有delete,update *** 作时,mybbs表中的id也会被级联删除或更新。如果没有选中,是不可以对author表中已被mybbs表关联的id进行update或者delete *** 作的。

拓展资料:

SQL的主键和外键的作用:

1、插入非空值时,如果主键表中没有这个值,则不能插入。

2、更新时,不能改为主键表中没有的值。

3、删除主键表记录时,你可以在建外键时选定外键记录一起级联删除还是拒绝删除。

4、更新主键记录时,同样有级联更新和拒绝执行的选择。

简而言之,SQL的主键和外键就是起约束作用。


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

原文地址: http://outofmemory.cn/bake/11572013.html

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

发表评论

登录后才能评论

评论列表(0条)

保存