兩種方法,命令與圖形化
圖形化,在控制臺(tái)左邊的小窗格中,找到要設(shè)置的表格名,右鍵,新建外鍵,然后根據(jù)要求設(shè)置既可。(新建關(guān)系圖-->添加表 然后直接用鼠標(biāo)拖字段連接就可以建立外鍵約束了 )
命令方式
sql ce表中建立外鍵約束的語法:CREATE TABLE DetectTable(UserID integer,StartTime datetime not null,EndTime datetime not null,MassName nvarchar(10), foreign key (UserID) references UserTable(UserID)),其中,UserID為UserTable表中的主鍵。
sql server中建立外鍵約束有3中方式:enterprise manager中,tables,design table,設(shè)置table的properties,可以建立constraint, reference key;enterprise manager中,diagrams, new diagrams,建立兩個(gè)表的關(guān)系;直接用transact sql語句。
1、三個(gè)方法都需要先建立數(shù)據(jù)表。
1)創(chuàng)建表author :
create table [dbo].[author] (
[id] [bigint] not null ,
[authorname] [char] (10) null ,
[address] [char] (480) null ,
[introduction] [ntext] null
)
2)創(chuàng)建表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、設(shè)置表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兩個(gè)選項(xiàng),指明以后author表的id字段有delete,update操作時(shí),mybbs表中的id也會(huì)被級(jí)聯(lián)刪除或更新。如果沒有選中,是不可以對(duì)author表中已被mybbs表關(guān)聯(lián)的id進(jìn)行update或者delete操作的。
SQL的主鍵和外鍵的作用:
1、插入非空值時(shí),如果主鍵表中沒有這個(gè)值,則不能插入。
2、更新時(shí),不能改為主鍵表中沒有的值。
3、刪除主鍵表記錄時(shí),你可以在建外鍵時(shí)選定外鍵記錄一起級(jí)聯(lián)刪除還是拒絕刪除。
4、更新主鍵記錄時(shí),同樣有級(jí)聯(lián)更新和拒絕執(zhí)行的選擇。
簡而言之,SQL的主鍵和外鍵就是起約束作用。
兩種方法,命令與圖形化
圖形化,在控制臺(tái)左邊的小窗格中,找到要設(shè)置的表格名,右鍵,新建外鍵,然后根據(jù)要求設(shè)置既可。(新建關(guān)系圖-->添加表 然后直接用鼠標(biāo)拖字段連接就可以建立外鍵約束了 )
命令方式
sql ce表中建立外鍵約束的語法:CREATE TABLE DetectTable(UserID integer,StartTime datetime not null,EndTime datetime not null,MassName nvarchar(10), foreign key (UserID) references UserTable(UserID)),其中,UserID為UserTable表中的主鍵。
展開表Orders
在表Orders右鍵,選擇設(shè)計(jì)
在右鍵中選擇關(guān)系
點(diǎn)擊添加
增加了一個(gè)自動(dòng)命名的外鍵,點(diǎn)擊"表和列規(guī)范"設(shè)計(jì)外鍵和主鍵列
選擇好主鍵列和外鍵列
點(diǎn)擊確定進(jìn)行保存
點(diǎn)擊關(guān)閉退出外鍵關(guān)系框
ctrl+s保存表結(jié)構(gòu)
刷新表Orders的鍵,可以發(fā)現(xiàn)外鍵已經(jīng)添加成功。
相關(guān)推薦: