代码及解释
4.1
create table book(
book_id nchar(6) not null,
book_name nchar(30) null,
price numeric(10,2) null
constraint PK_book_id primary key clustered(
book_id asc
)
)on [primary]
create table author(
author_name nchar(4),
book_id nchar(6),
address nchar(30),
)on [primary]
alter table author
with check
add constraint FK_book foreign key(book_id)
references book(book_id)
解释: 1.constraint为约束,PK_book为主键索引名,clustered为聚集索引(就是将数据排序后再加上索引) 2.asc为按值升序 3.on[primary]在主文件组,可以不加 4.references后面是主键表的主键 5.外键就是一个关系的属性在另一个关系中为主键,则称这个属性为外键 6.with check 7.创建表的结构:名字+类型+是否为空
4.2
use test01
create table booksales
(
book_id nchar(6) null,
sellnum int null,
selldate date null
)
insert into booksales(book_id,sellnum,selldate)
values('1',2,'2019-03-30')
insert into booksales
values('2',3,'2019-12-12')
update booksales
set selldate='2013-01-1'
where book_id='2'
delete from booksales
where book_id='1'
解释: 1.date要记得加上引号,格式为’yyyy-mm-dd’
4.3
use test01
go
create rule sell_rule
as
@sells>=0
go
sp_bindrule 'sell_rule','booksales.sellnum'
解释: 1.创建规则的语句一定要用go语句,否则会报错:create rule要使用批处理语句 2.代码中@sells可以改为任意字符但是要加@符号
4.4
delete from booksales
where year(selldate)<2015
truncate table booksales
drop table booksales
解释: 1.数据库日期类型数据可以直接比较例如selldate<‘1/1/2015’
参考资料
创建主键 数据库索引 索引命名规范 聚集索引和非聚集索引(整理) 数据库的索引与主键
|