以下的运用文章那个主要是向大家讲述的是 SQL Server创建约束的实际应用代码。在SQL Server数据库中,建约创建约束的代码方式主要有两种,一种是运用在创建数据库表使同时创建约束,另外一种就是建约数据库表创建号之后再创建约束。
约束的代码类型一共有五种,分别为:主键约束(primary key),运用外键约束(foreign key),建约检查约束(check),代码默认约束(default)和唯一约束(unique)。运用
- Sql代码
- --创建借阅表
- 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)
- )
- --创建借阅表
- 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代码
- --追加默认
- alert table Readers
- add constraint DF_ReturnDate
- default (getdate()) for ReturnDate
- --追加默认
- alert table Readers
- add constraint DF_ReturnDate
- default (getdate()) for ReturnDate
我把追加默认约束单独那出来,可以发现它是代码和其它约束的写法不一样的,以上的运用相关内容就是对SQL Server创建约束的介绍,望你能有所收获。
【编辑推荐】
责任编辑:佚名 来源: FT中文网 SQL Server创建约束
(责任编辑:焦点)
江西省一季度国有经济亮出成绩单 国有企业资产规模达到6.1万亿元
iOS 15新发现:微信在后台反复读取用户相册 QQ等也做同样动作
英特尔官宣新主题活动 将发Meteor Lake和Emerald Rapids