实验三数据库数据插⼊、修改和删除
【实验⽬的】
1.熟悉使⽤update/insert/delete语句进⾏表操作。
2.能将这些更新操作应⽤于实际操作中去。
【实验环境】
Windows 10系统 + SQL Server 2012php修改数据库内容
【实验内容】
基于实验⼀EDUC数据库中建⽴的表,完成以下实验内容:
对于student表,将所有专业号为‘sp01’的并且⼊学年份为2013年9⽉1⽇的学⽣的班级号改为‘C01’。
2.对于student表,删掉所有年龄⼩于20 岁,并且专业号为‘sp03’的学⽣的记录。
3.对于student表,插⼊⼀条新记录,学号:13030004、姓名:张三、性别:男、出⽣⽇期:1995-08-08、专业代码:‘sp03’、班级号:‘0302’、⼊学时间:2013-09-01。
4.对于student表,将年龄最⼩的学⽣的⼊学时间去掉。
5.对于student表,将平均年龄最⼩的⼀个院系的专业代码改为‘new1’。
1.在开始菜单中选中SQL Server Management Studio图标,启动SSMS。启动后,单击“连接”按钮,进⼊SSMS窗⼝。如下图所⽰:
图1
2.本次实验均基于EDUC数据库中student表,其原数据内容如下图所⽰:
图2
3.编写语句,对于student 表,将所有专业号为‘sp01’的并且⼊学年份为2013年9⽉1⽇的学⽣的班级号改为‘C01’。
①update student set classno = 'C01'
where spno = 'sp01' and entime = '2013-09-01'
②update student set classno='C01'
where spno = 'sp01' and year(entime) = 2013
结果如下图所⽰:
图3
4.编写语句,对于student 表,删掉所有年龄⼩于20岁,并且专业号为‘sp03’的学⽣的记录。
delete student
where spno = 'sp03' and year(getdate()) - year(birthday) < 20
由于原表中没有符合条件的记录,故此处不做截图。
5.编写语句,对于student 表,插⼊⼀条新记录,学号:13030004、姓名:张三、性别:男、出⽣⽇期:1995-08-08、专业代码:‘sp03’、班级号:‘0302’、⼊学时间:2013-09-01。
①insert into student (sno, sname, sex, birthday, spno, classno, entime)
values('13030004', ’张三', '男', '1995-08-08', 'sp03', '0302', '2013-09-01')
②insert into student
values('13030004', ’张三', '男', null, '1995-08-08', null, 'sp03', '0302', '2013-09-01')
结果如下图所⽰:
图4
6.编写语句,对于student 表,将年龄最⼩的学⽣的⼊学时间去掉。
update student set entime = null
where sno = (select top 1 with ties sno from student
order by birthday desc)
结果如下图所⽰:
图5
7.编写语句,对于student 表,将平均年龄最⼩的⼀个院系的专业代码改为‘new1’。
①update student set spno='new1'
where dno=(select top 1 dno from student
group by dno order by avg(year(getdate())-year(birthday)))
②select top 1 dno,avg(year(getdate())-year(birthday)) 平均年龄
into #b from student
group by dno order by平均年龄
update student set spno='new1'
where dno=(select dno from #b)
结果如下图所⽰:
图6
【实验结果】
本次实验结果已在【实验⽅法和步骤】中列出,此处不再重述。
【总结】
①insert:在insert语句中使⽤select⼦句,不能把select⼦句写在圆括号中。insert语句中的列名列表应当放在圆括号中,并且不使⽤values关键字。若源表与⽬标表结构完全相同,则可省略insert语句中的列名列表。select⼦句中的列列表必须与insert语句中的列列表相匹配。若没有在insert语句中给出列列表,select⼦句中的列列表必须与⽬标表中的列相匹配。
②update:在update语句中使⽤select⼦句,可将⼦查询的结果作为修改数据的条件,并且select⼦句要写在圆括号中。
③delete:在delete语句中使⽤select⼦句,可将⼦查询的结果作为删除数据的条件,并且select⼦句要写在圆括号中。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。