SQL Server創(chuàng)建約束的代碼運(yùn)用
以下的文章那個(gè)主要是向大家講述的是 SQL Server創(chuàng)建約束的實(shí)際應(yīng)用代碼。在SQL Server數(shù)據(jù)庫中,創(chuàng)建約束的方式主要有兩種,一種是在創(chuàng)建數(shù)據(jù)庫表使同時(shí)創(chuàng)建約束,另外一種就是數(shù)據(jù)庫表創(chuàng)建號(hào)之后再創(chuàng)建約束。
約束的類型一共有五種,分別為:主鍵約束(primary key),外鍵約束(foreign key),檢查約束(check),默認(rèn)約束(default)和唯一約束(unique)。
- Sql代碼
- --創(chuàng)建借閱表
- create table Borrows
- (
- BSID int identity(1,1),
- BID int not null foreign key references Books(BID),
- RID int not null foreign key references Readers(RID),
- BorrowDate datetime default(getdate()),
- ReturnDate datetime,
- primary key(BSID)
- )
- --創(chuàng)建借閱表
- create table Borrows
- (
- BSID int identity(1,1),
- BID int not null foreign key references Books(BID),
- RID int not null foreign key references Readers(RID),
- BorrowDate datetime default(getdate()),
- ReturnDate datetime,
- primary key(BSID)
- )
- Sql代碼
- --添加約束
- alter table Readers
- add constraint CK_RaderAge
- check(rage between 15 and 60)
- --追加主鍵
- alter table Readers
- add constraint PK_Reader
- primary key (RID)
- --追加外鍵
- alter table Borrows
- add constraint FK_Book
- foreign key (BID) references Books(BID)
- --添加約束
- alter table Readers
- add constraint CK_RaderAge
- check(rage between 15 and 60)
- --追加主鍵
- alter table Readers
- add constraint PK_Reader
- primary key (RID)
- --追加外鍵
- alter table Borrows
- add constraint FK_Book
- foreign key (BID) references Books(BID)
- Sql代碼
- --追加默認(rèn)
- alert table Readers
- add constraint DF_ReturnDate
- default (getdate()) for ReturnDate
- --追加默認(rèn)
- alert table Readers
- add constraint DF_ReturnDate
- default (getdate()) for ReturnDate
我把追加默認(rèn)約束單獨(dú)那出來,可以發(fā)現(xiàn)它是和其它約束的寫法不一樣的,以上的相關(guān)內(nèi)容就是對SQL Server創(chuàng)建約束的介紹,望你能有所收獲。
【編輯推薦】
- 解決SQL Server數(shù)據(jù)庫中的安全疑難問題的方案
- 對SQL Server數(shù)據(jù)庫與XML支持的正確理解
- SQL Server刪除群集的實(shí)例演示
- SQL Server主鍵列的正確查看方式
- SQL Server數(shù)據(jù)庫與XML支持的正確解析經(jīng)典版