此题应该是建表和插入数据的经典题目
1. 先建立表(Sno代表学号,sname代表姓名,ssex代表性别,sage代表年龄,sdept代表所在系,cno代表课号,cname代表课程名称,cpno代表先修课号,ccredit代表学分,grade代表成绩)
create table student( sno char(5),
sname varchar(10) not null,
ssex char(2),
sage smallint constraint DF_student_sage default(20),
sdept varchar(20),
constraint PK_student_sno primary key(sno),
constraint CK_student_sage check(sage>0) )
create table course
( cno char(2),
cname varchar(20) not null constraint UQ_course_cname unique,
cpno char(2),
ccredit smallint constraint DF_course_ccredit default(2),
constraint PK_course_cno primary key(cno),
constraint CK_course_ccredit check(ccredit>0),
constraint FK_course_cpno foreign key(cpno) references course(cno) )
create table sc
( sno char(5),
cno char(2),
grade int,
constraint PK_sc_sno_cno primary key(sno, cno),
constraint FK_sc_sno foreign key(sno) references student(sno),
constraint FK_sc_cno foreign key(cno) references course(cno),
constraint CK_sc_cno check(grade>0) )
2. 将记录插入到表中
insert into student(sno, sname, ssex, sage, sdept) values('95001', '李勇', '男', 20, 'CS')insert into student(sno, sname, ssex, sage, sdept) values('95002', '刘晨', '女', 19, 'IS')
insert into student(sno, sname, ssex, sage, sdept) values('95003', '王敏', '女', 18, 'MA')
只要会建表语句和插入语句即可
CREATE TABLE <表名>( <列名> <数据类型> [not null] [[constraint 约束名] default (缺省值)] [[constraint 约束名] unique]
[,其他列的定义]…
[,[constraint 约束名] primary key(列名[, 列名] …)]
[,[constraint 约束名] foreign key(列名[, 列名] …) references 表名(列名[,列名] …)]
[,[constraint 约束名] check(条件)] )
INSERT [INTO] <表名>[(<列名> [,<列名>…] ) ] VALUES(<表达式> [,<表达式>…] )
--基础题--1.查询读者最喜爱的3种图书分类号,即借阅表中出现最多的3类图书分类号
SELECT TOP 3 [分类号] FROM [图书] JOIN [借阅] ON [图书].[图书编号]=[借阅].[图书编号]
GROUP BY [分类号] ORDER BY COUNT(*) DESC
--附加题
--1.查询小于20岁的读者最喜欢的3类图书
SELECT TOP 3 [书名] FROM [读者] JOIN [借阅] ON [读者].[借书证号]=[借阅].[借书证号]
JOIN [图书] ON [图书].[图书编号]=[借阅].[图书编号]
WHERE [年龄]<20 GROUP BY [书名] ORDER BY COUNT(*) DESC
--2.查询至少借阅了 宁静 所借图书(书名相同)的人的姓名
SELECT [姓名] FROM [读者] WHERE [姓名]<>'宁静' AND [借书证号] IN(SELECT [借书证号] FROM [借阅]
WHERE [图书编号] IN(SELECT [图书编号] FROM [读者] JOIN [借阅] ON [读者].[借书证号]=[借阅].[借书证号] WHERE [姓名]='宁静'))
--3.查询借阅了多于3本书且每本书价均高于60的读者的借书证号
SELECT [借书证号]
FROM [借阅] JOIN [图书] ON [图书].[图书编号]=[借阅].[图书编号]
WHERE [单价]>60 GROUP BY [借书证号] HAVING COUNT(*)>3
GO
--4.假定读者表中所有人姓名均不多于4个汉字,请建立一个查询语句,要求根据名字中任意1个或两个或3个或4个汉字,即可找到该读者的详细信息(即完全模糊查询)
CREATE PROCEDURE CX
@XM VARCHAR(8) AS
IF LEN(@XM)=1 SELECT * FROM [读者] WHERE @XM LIKE '['+RTRIM([姓名])+']'
ELSE IF LEN(@XM)=2 SELECT * FROM [读者] WHERE LEFT(@XM,1) LIKE '['+RTRIM([姓名])+']' AND RIGHT(@XM,1) LIKE '['+RTRIM([姓名])+']'
ELSE IF LEN(@XM)=3 SELECT * FROM [读者] WHERE LEFT(@XM,1) LIKE '['+RTRIM([姓名])+']' AND SUBSTRING(@XM,2,1) LIKE '['+RTRIM([姓名])+']' AND RIGHT(@XM,1) LIKE '['+RTRIM([姓名])+']'
ELSE IF LEN(@XM)=4 SELECT * FROM [读者] WHERE LEFT(@XM,1) LIKE '['+RTRIM([姓名])+']' AND SUBSTRING(@XM,2,1) LIKE '['+RTRIM([姓名])+']' AND SUBSTRING(@XM,3,1) LIKE '['+RTRIM([姓名])+']' AND RIGHT(@XM,1) LIKE '['+RTRIM([姓名])+']'
GO
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)