新聞中心
我們今天主要向大家介紹的是SQL Server外鍵約束與SQL Server建立外鍵約束的3種方案的介紹,我前兩天在相關(guān)網(wǎng)站看見SQL Server建立外鍵約束的3種方案的資料,覺得挺好,就拿出來供大家分享。

1.Enterprise Manager中,Tables,Design Table,設(shè)置Table的properties,
可以建立constraint, reference key;
2.Enterprise Manager中,Diagrams, new Diagrams,建立兩個表的關(guān)系。
3.直接用transact sql語句。
三個方法都需要先建立數(shù)據(jù)表。
創(chuàng)建表author :
- CREATE TABLE [dbo].[author] (
- [ID] [bigint] NOT NULL ,
- [AuthorName] [char] (10) NULL ,
- [address] [char] (480) NULL ,
- [introduction] [ntext] NULL
- )
創(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
- )
設(shè)置表myBBS中的authorId為外鍵,參照author表的Id字段,直接使用transact sql語句,過程如下:
增加表mybbs(authorId)的SQL Server外鍵約束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
刪除SQL Server建立外鍵約束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也會被級聯(lián)刪除或更新。如果沒有選中,是不可以對author表中已被myBBS表關(guān)聯(lián)的id進(jìn)行update或者delete操作的。
文章標(biāo)題:SQLServer外鍵約束與建立外鍵約束的方案
分享地址:http://m.fisionsoft.com.cn/article/cdshdge.html


咨詢
建站咨詢
