SQL实验(实验4至实验7的答案)
- 格式:doc
- 大小:480.00 KB
- 文档页数:21
实验四SQL语言【实验目的】1.掌握SQL语言的使用方法2.利用SQL语句实现相关的操作3.能够独立写出一些较复杂的SQL语句【实验内容】1. 建立一个Student表,由Sno(学号)、Sname(姓名)、Ssex(性别)、Sage(年龄)、Sdept (所在系)五个属性组成。
其中学号不能为空,值是唯一的,并且姓名取值也唯一。
查询名为“创建Student”。
Create table student(sno char(6) not null unique,sname char(4) unique,ssex char(1),sage smallint,sdept char(20))2. 建立一个SC (学生选课)表,它由学号Sno、课程号Cno,修课成绩Grade组成,其中(Sno, Cno)为主码。
),查询名为“创建SC”。
Create table sc(sno char(6),cno char(3),grade single,primary key (sno,cno))3. 查询所有姓刘的学生的学号与姓名及其出生年份,查询名为“查找姓刘的学生”。
Selelct 学号,姓名,year(出生日期) as 出生年份from 学生表where 姓名like “刘*”4. 查询选修了计算机基础的所有学生的学号、姓名、成绩,查询结果按分数降序排列,查询名为“选修了计算机基础的学生”。
Select 学生表.学号,学生.姓名,选课成绩表.成绩from 学生表,课程表,选课成绩表where 学生表.学号=选课成绩表.学号and 课程表.课程编号=选课成绩表.课程编号and 课程表.课程名称=”计算机基础” order by 选课成绩表.成绩6. 查询所有年龄在20岁及20岁以下的学生姓名、年龄,查询名为“20岁及以下的学生”。
Select 姓名,年龄from 学生表where year(date())-year(出生日期)<=207. 查询考试成绩有不及格的学生的学号和姓名。
SQL实验报告(优秀范文5篇)第一篇:SQL实验报告实验四触发器实验(一)after触发器(1 1)在l l i neitem 表上定义一个 after 触发器, , 当修改列项目e e xtendedprice d i scountx tax 时, , 要把 s orders 表得to o tal pri ce e 一起修改, , 以保证数据一致性C RE ATE T RIGGERtrig _line ite m_ pr ice_ update on line it em fo rupda teaasbegin i f(UPDATE(ex tend edprice)o r UPDATE(tax)or UPD AT E(di scou nt))begin-—声明游标变量指向 inserted 表d eclarecursor_inserted c urs orrea d_onlyofor select order key,linenu mber,exte nd edpr ice, dis coun t, taxfromin ser ted—-息信找查取获量变明声ﻩ声明变量获取查找信息de clare order key in t, @linenumb erint,exte nd edpricereal,disscount real,tax real—-打开游标epoﻩen cursor_i ns ert ed—-标游取读ﻩ读取游标fe tchnextfrom cur sor _i ns erte dint o@o rderkey, @lin enumber,eext ende dprice, @di scount,t axwwhi le FETC H_S TATUS =0 nigebﻩnﻩ—-声明一个变量保存重新计算得新价格cedﻩﻩecl are @n ew_tota lpri cer ealﻩ select @n ew_t otal price= @ext en dedpr ice *(1 -@di scou nt)*(1 +@tax)—-用新得总价格变量更新 orders 表得 t ot alprice puﻩﻩupdate orde rsse t tot alpri ce= new_totalprice where or derkey=orde rkeyen hctefﻩext f ro m cur sor_i nser ted int o@order ke y, @li nenum ber, @ex tende dp rice,discoun t, @taxdneﻩllaedﻩlocate c ur sor_i nser te deend end ﻩ(2)在在 linei tem表上定义一个 aftr er 触发器, , 当增加一项订单明细时, ,自动修改 s orders 表得 total p rice, 以保证数据一致性CREATE TR IGGER tri g_ lineit em_price_ in sert on l ine item ffor inse rta sbegin ——向指量变标游明声ﻩ声明游标变量指向ins erted 表de clarec ursor_inse rtedcursorread_ onl yﻩ for s ele ct orderkey,linenumbe r,ex te ndedp ric e,di scou nt,t axfrom insserte d--声明变量获取查找信息edﻩeclare @orde rk eyint, @lin enumber int,e xten dedp ricereal, @discountreal, @ta xreal -—ﻩ-打开游标open cursor_i ns erte d--ﻩ-读取游标fe tc hnex tf romcu rsor_ins ertedinto@o rd erkey,li nen umbeerr, ex ten ded pric e,dis count,tax ihwﻩile @@FE TCH_ STATU S=0 ebﻩegin-—格价新得算计新重存保量变个一明声ﻩﻩ声明一个变量保存重新计算得新价格cedﻩclare @n ew_tot alprice realcelesﻩct new _to ta lprice= @extend edp rice *(1-d is count)*(1+tax)—-新更量变格价总得新用ﻩﻩ用新得总价格变量更新orders 表得totalpri ceﻩ u pda teor ders s ett ota lpric e=total pric e+ @new_ tota lpr ice wwhhe re o rderke y=orderkeytefﻩetch next from cursor_ ins erte dinto o rder key, @l inen umber,e xtendeddp ric e, @disc ou nt, @t axeend aedﻩdeall oca te cu rsor_in serted en d(3)在l in e ite m表上定义一个a ft er触发器, , 当删除一项订单明细记录时, ,自动修改 orders 表得 tot a lprice, 以保证数据一致性CREATE TRI GG ER trig _line item_price_de let eon line item fo r de let eAAS begin--声明游标变量指向delet ed 表de clar e curso r_d eleted cursorre ad _on lyesrofﻩﻩele ctord erk ey,line numbe r,extende dp rice,discoun t, taxfromdel eted-ﻩ--声明变量获取查找信息declare ord erkey int,linenum be rint,extendedp ri ce r eal,discou nt real,ta xreal -—ﻩ-打开游标epoﻩen c urso r_ deleted——标游取读ﻩ读取游标efﻩetch next fr om cur sor_delete d in toorder ke y,l inenumb er,ext enddedprice, @di scoun t,taxwh ile@FETCH_STATUS=0begi n-—声明一个变量保存重新计算得新价格ﻩ declare @ne w_ to talpric erealﻩsselec t@new_t otalpr ice= @exte nde dpri ce*(1-@disco unt)*(1+ tax)-ﻩ-—用新得总价格变量更新orders 表得tot alp rice uﻩﻩupd ateorders set t otalpri ce=to talpr ice-@new _totalp rice wh er e order key= @ord erkeyfetchn ext f rom cursor_inse rt ed in to orderkey, @line numbe r,extendeeddprice, @d iscou nt,t ax dneﻩndddeal lo cat e cur sor_inse rted eend((4 4))验证 up d at e触发器—-查瞧号订单得 to ta a l pr i ceselec t*fro o mo o r ders whereorde r key=1 8 30;—-查瞧明细表得相关信息se l ect *f ro mlin ei i te e mw here or de e r key=183 0and l ine num m be e r =1;——验证 e update 触发器updat elineitem set t ax=tax+0、05whe re orderkey=1830;(二)i i n steadof触发器((1))在在 lineit em 表上定义一个ins tead o fupda te触发器, 当修改明细表中得数量量quan ti ty 时, 应先检查供应表par tsupp 得av ai lqty 就是否足够, 不足够则拒绝执行, 否则执行并修改相应数值以保证数据一致性于由于 in steadof 触发器更新某个表会使得该表上其她不满足更新列不能更新,因因用此逆向思维使用 a fter 触发器实现相同效果即先更新 qu antity, 再比较av ailqqtty, 如果满足更新数量, 就修改partsupp 得表得 a vailqty, 如果不满足, 则把lineitem得quantity 更新之后得数据重新修改回来ccreate trigge r trig_lin eit em_quanti ty_ upda teonli neit em f or upda teas begin if UPDATE(qu ant ity)bbegin ——向指别分量变标游明声ﻩ声明游标变量分别指向 i nserted 表与 d el eted 表edﻩdeclare c urso r_inser tedcur sorr ead_on lyfortcelesﻩﻩtorde rkey, partk ey,s uppkey,lin enum ber, quantit yfr om i nserteddecl arecursor_de leted c urs orrea d_ onl yf or select quantityfr om deleted-—息信找查取获量变明声ﻩ声明变量获取查找信息decl are@qu an tity _dif f_lineitem i nt,q uanti ty_pa rtsup p i nt cedﻩclare suppkey int, @par tke y in t,o rd erkey i nt,unenilﻩﻩum ber int ,qty _inserted in t , @qty_deleted int--打开游标ruc nepoﻩrsor_in sert ed poﻩopen cur sor_d eleted-—量变给赋值数标游取读ﻩ读取游标数值赋给变量fﻩfet chnext fromcu rsor_ insert edﻩiinto or de rk ey,pa rtkey, @suppk ey, @line nu mber, @qty _ins erte df et chnext fromcursor _d eletedint o q ty _de lete dwhi le fe tch_st atus=0 gebﻩegin--计算订单明细修改时, 订购数量得变化值inserte d表项-d elet ed表项ssel ect quantity_d if f_ li neit em= @q ty _in se rte d—@@q ty_deleteedﻩ--从parts upp 表获取ava ilq ty值, 注意partsupp 表得主键为(partk ey,suppkeey)tcelesﻩﻩt@quanti ty_p ar tsupp =av ailq ty fro m pa rtsu ppwﻩﻩwh er e suppkey= suppke yand part key= @par tk ey-—断判始开ﻩﻩ开始判断gebﻩbegi nfiﻩf quant ity _d iff_ lin eite m=0ﻩﻩ p rin t“ 更新得数量与原表中得值相同, 不需要更新”e ls eif @quantit y_d iff_lin eitem 〈=q uantity_partsuppﻩbe ginﻩpuﻩﻩpd ate partsupps et avail qty= availqty-@qua ntit y_d iff_li ne item ﻩpus erehwﻩppkey=suppkeyandp artkey= @par tke yﻩﻩ p rint “ 两个表都更新成功’ ﻩﻩﻩneﻩndels eigebﻩﻩinﻩuﻩﻩupdate li nei temsetquantit y=quantity+ @quanti ty_diff_linei temwhe re o rd erke y=@orde rke y and li nenu mber= @liine numberﻩp ri nt '更新失败”ﻩﻩendﻩ e nd efﻩﻩetch ne xtfr om c urso r_i nsertedi nto @ord erke y, @partkey,s upp key, @linenumb er, @qt y_ ins ert edf etch ne xt from curso r_de leted into @qt y_d elet ed dneﻩndd eallocat e cur sor _i nserte ddealloc at e cursor_de le ted eend eend(2)在在 l ineite m表上定义一个 instea d of in sert 触发器, 当插入明细表中一条记录时时, 应先检查供应表par tsupp 得得 ava il qt y就是否足够qu anti ty 得数量c rea te t rig ger tri g_lineitem_q ua nti ty_ insertonline item iinstead of inser t as bbegin-—声明游标变量指向 inserte d表d eclar e cur sor_inserte dcur sorrea d_ only f orsﻩﻩselect or derk ey,pa rtkey,sup pk ey, lin en umber,q uantityf rom ins er ted-—声明变量获取查找信息dec lare quantity int, @av ailq ty i nt, @suppkeyin t, @partkeyinntt, @o rderkey int, @linenu mber int-—标游开打ﻩ打开游标c nepoﻩcurs or_ins erted -ﻩ-—读取游标f etc hnext fro mcursor_insert edint o@orde rkey,partkey,@@ssuppkey, @linenumber,qu antity wh ile @@FETCH_S TATUS= 0igebﻩin--为变量赋值a tcelesﻩavailqtyy==av ai lqt y fr ompartsuppwﻩwhe re suppkey =@su ppk ey and part ke y= partke yﻩ if @quant ity 〈= @avail qt y-—如果可以更新bﻩbegin /ﻩﻩﻩ/*将将 insert ed 表中得记录插入到明细表*/ ﻩsniﻩserti nto l ineite m select *from i nsertedro=yekredroerehwﻩﻩrderk ey andlinenumb er = @linenumber */ﻩﻩ新更时同ﻩ*同时更新 part supp 表得数量*/ﻩﻩuupd ate pa rtsup pset a vailqty=availqty-@quanti tyﻩerehwﻩe sup pke y= @sup pkey and partkey=part key ppr int ’paarts upp 表有足够得货物可以满足 lin eitem 得quan tityy, 插入成功’endelsebeginﻩﻩ p rintt''pa rt sup p表没有足够得货物可以满足 l ineitem 得得q uantity,插入失败’dneﻩfﻩﻩfetc h next from curso r_ins ert ed in to@ord erkey, partkey, suppkey, @liinenumbe r, qu antity eﻩen ddeall ocat ecursor_ inserted end(3)在在 line ite m表上定义一个 inste ad of del ete 触发器,当当删除明细表中记录时时, 同时改变表供应表 partsupp 得ava il qtyy数值 c re ate trigge r tri g_ lin eit em_quanti ty_ del ete o n line item inste ad of del ete as be gin—-声明游标变量指向deleted 表de cla re curs or_ del eted c ursorread _only forlesﻩﻩelect or derke y, par tkey,sup pkey, linenumbe r,quan tity fr om deleted -ﻩ--声明变量decl are s upp key i nt, par tke yint, @orde rkey int,linen umb erint, @quaant it y int—-标游开打ﻩ打开游标opencursor_deleted-—标游取读ﻩ读取游标ffetch next fr omcurs or _del et edin to @ord erkey , @partkey,s uppkeey, @lin en umber,q ua ntitywhi leFFET CH_ STATUS=0 igebﻩin*/*除删ﻩ*删除*/ﻩ de let e fromlineite m where linenu mber= line number and o rde rkey =ordder key*/新更时同ﻩ同时更新 pa rt supp 表得数量*/u pdateparts uppse tavailqt y=a vai lq ty+quant ityﻩ where s uppke y= @s uppkey a nd par tk ey= @p ar tkeyﻩ p rin t’ 删除成功, 并且已经把货物数量归还到 p ar tsup p里“ fﻩﻩfetc h ne xt fr omcurso r_del etedinto @ord er ke y,p ar tkey,@@suppkey, @lin enu mber,quanti ty neﻩnd edﻩea lloc ate cursor_ delete dend(4)验证 update 触发器--查瞧li neit em 得quan tit y select*fr omlin eit em whe re or derk ey =1830and li nenum ber=1;——查询partsupp 表得ava ilqt y se lect * from part supp w here suppk ey =(selectsupp key fr omlin eitem w here ord erkey=18 30)and partk ey=(s elec t part key from lin eite mwh er eorder key =18 30 a nd linenu mber=1)---更新数量过大——更新得值与原值相同---更新到+ + 2 00 数量, , 成功updateli neitem setquant ity=q uanti ty+ 200where order key=1830and lin en umber =1;--更新 +2 00成功后l ineite m得 quanti ty y 变化——更新+200 成功后par ts upp 表得a va ilqty 变化实验到此。
SQL-Server实验答案上海师范大学计算机系目录第一部分企业管理器的使用 (3)试验一注册服务器.................................................................................. 错误!未定义书签。
试验二创建数据库.................................................................................. 错误!未定义书签。
试验三创建表.......................................................................................... 错误!未定义书签。
实验四数据输入...................................................................................... 错误!未定义书签。
实验五登录到数据库服务器.................................................................. 错误!未定义书签。
第二部分SQL语言 (3)第二部分SQL语言 (3)试验一数据库创建 (3)试验二创建表 (3)试验三创建数据完整性 (5)试验四数据完整性试验 (6)试验五索引 (10)试验六更新数据 (11)试验七 Sql 查询语句 (12)试验八视图 (15)试验九安全性控制实验 (16)试验十存储过程 (17)试验十二触发器 (21)试验十二恢复技术 (25)试验十三事务 (26)试验十四锁 (27)第一部分企业管理器的使用第二部分SQL语言试验一数据库创建目的:1掌握利用SQL语言进行数据库的创建、维护。
2 sp_helpdb 命令要求:1 创建数据库 2 修改数据库 3 删除数据库一建立school 数据库1 使用查询分析器创建数据库 schoolCreate DataBase school2 使用 SP_helpdb 查询数据库 School 的信息3 使用SQL-Server 的企业管理器查看数据库 school 的信息。
数据库原理SQLServer实验指导书数据库系统原理实验一、基本操作实验实验1:数据库的定义实验本实验的实验目的是要求学生熟练掌握和使用SQL、T-SQL、SQL Server Enterpriser Manager Server 创建数据库、表、索引和修改表结构,并学会使用SQL Server Query Analyzer,接收T-SQL语句和进行结果分析。
本实验的内容包括:l)创建数据库和查看数据库属性。
2)创建表、确定表的主码和约束条件,为主码建索引。
3)查看和修改表结构。
4)熟悉SQL Server Enterpriser Manager和 Query Analyzer工具的使用方法具体实验任务如下。
1.基本提作实验1)使用Enterpriser Manager建立图书读者数据库2)在Enterpriser Manager中查看图书读者数据库的属性,并进行修改,使之符合要求。
3)通过Enterpriser Manager,在建好了图书借阅数据库中建立图书、读者和借阅3个表,其结构为:图书(书号,类别,出版社,作者,书名,定价,版次);读者(编号,姓名,单位,性别,电话):借阅(书号,读者编号,借阅日期人)要求为属性选择合适的数据类型,定义每个表的主键,Allow Null(是否允许空值)和Default Value(缺省值)等列级数据约柬。
4)在Enterpriser Manager建立图书、读者和借阅3个表的表级约束:每个表的PrimaryKey (主键)约束;借阅表与图书表间、借阅表与读者表之间的FOREIGNKEY(外码)约柬,要求按语义先确定外码约束表达式,再通过操作予以实现;实现借阅表的书号和读者编号的UNIQUE(惟一性)约束;实现读者性别只能是“男”或“女”的check(检查)约束。
2.提高操作实验建立学生_课程库操作,在查询分析器中用SQL命令实现。
库中表结构为:Student(sno,sname,sage,ssex,sdept):course(cno,cname,cpno,ccredit);sc(sno,cno,grade)。
SQL实验报告姓名:何静班级:息082班学号:089094288实验1:1.3.1利用循环计算10!的值。
代码:declare @a int,@b intset @a=1set @b=1while @a<=10beginset @b=@a*@bset @a=@a+1endprint @b运行截图:1.3.2利用WHILE循环计算当前时间距离2012年3月1日之间的天数。
代码:DECLARE @num int , @sj DA TETIMESET @sj = GETDA TE()PRINT '当前时间为:' + CAST( @sj AS CHAR(20))SET @num=0WHILE 1=1BEGINSET @sj = DA TEADD(day,1,@sj)SET @num = @num + 1IF DA TEPART( yy , @sj ) = 2012BREAKENDPRINT '距离2012年3月1日还有' + CAST(@num AS V ARCHAR(10)) + '天'运行截图:实验2数据查询:【实验2-1】向“学生基本信息表”中添加“电子邮件“列。
ALTER TABLE 学生基本信息表ADD Email varchar(20) NULL截图:【实验2-2】将“学生基本信息表”中的“姓名”列改为最大长度为20的varchar 型数据,且不允许空值。
alter table 学生基本信息表alter column 姓名varchar(20) not null截图:【实验2-3】使用SQL向“学生基本信息表”中输入一行数据:(学号:‘000107’,姓名:’巴尔夏提’,家庭住址:’新疆库尔勒市’)。
INSERT INTO 学生基本信息表(学号,姓名,家庭住址)V ALUES ('000107','巴尔夏提','新疆库尔勒市')截图:【实验2-4】删除“学生基本信息表”中姓名为杨文利的学生记录。
实验四简单查询和连接查询1. 简单查询实验用Transact-SQL语句表示下列操作,在“学生选课“数据库中实现其数据查询操作:(1) 查询数学系学生的学号和姓名。
select sno,snamefrom studentwhere dept='数学系';(2) 查询选修了课程的学生学号。
select distinct(sno)from sc;(3) 查询选修课程号为0101的学生学号和成绩,并要求对查询结果按成绩降序排列,如果成绩相同则按学号升序排列。
select distinct(sno),gradefrom scwhere cno='0101'order by grade desc,sno asc;(4) 查询选修课程号为0101的成绩在80-90 分之间的学生学号和成绩,并将成绩乘以系数0.8 输出。
select distinct(sno),grade*0.8 as'sore'from scwhere cno='0101'and grade between 80 and 90;(5) 查询数学系或计算机系姓张的学生的信息。
select*from studentwhere dept in('数学系','计算机系')and sname like'张%';(6) 查询缺少了成绩的学生的学号和课程号。
select sno,cnofrom scwhere grade is null;2. 连接查询实验用Transact-SQL语句表示,并在“学生选课”数据库中实现下列数据连接查询操作:(1) 查询每个学生的情况以及他(她)所选修的课程。
select student.*,amefrom student,sc,coursewhere student.sno=sc.sno and o=o;(2) 查询学生的学号、姓名、选修的课程名及成绩。
数据库实验总汇二、使用SQL Server 工具在管理数据库系统和运行SQL查询的两个主要工具是企业管理器和查询分析器三、实验目的1.熟悉数据库的交互式SQL工具。
2.熟悉通过SQL对数据库进行操作。
3.完成上机练习。
四、实验内容(打※为选做题)Part A1.使用CREATE语句创建数据库2. 使用CREATE语句创建基本表3.更改基本表的定义,增加列,修改列的数据类型。
4.创建表的索引,取消表的索引1、数据库的建立使用SQL 语句建立关系数据库schooldemo2、基本表的建立在数据库schooldemo下,使用SQL 语句建立关系数据库表:人员表PERSON(Pno,Pname, Page),房间表ROOM(Rno,Rname,Rarea),表PR(Pno,Rno,Date).其中,表PERSON :Pno(CHAR(8),主码,非空,唯一),Pname(CHAR(20),非空),Page(INT);表ROOM:Rno(CHAR(8),主码,非空,唯一),Rname(CHAR(20)),Rarea(FLOAT (10));表PR:Pno(CHAR(8),非空,唯一),Rno(CHAR(8),非空,唯一),Date (DATETIME);(三个表之间有联系)3、更改基本表的定义,增加列,删除列,修改列的数据类型。
更改表PERSON,增加属性Ptype(类型是CHAR ,长度为10),把表ROOM中的属性Rname的数据类型改为长度为40。
4、创建表的索引,取消表的索引为ROOM表创建按Rno降序排列的索引创建PERSON表按Pname升序排列的唯一性索引取消PERSON表Pname升序索引5、删除表ROOM实验过程(1.a)1、数据库的建立使用SQL 语句建立关系数据库schooldemocreate database schooldemoon(name=schooldemo,filename='e:\123\school_data.mdf',size=5mb,maxsize=15mb,filegrowth=10%)log on(name=schooldemo_log,filename='e:\123\schooldemo.ldf',size=5mb,maxsize=15mb,filegrowth=4mb)2、基本表的建立在数据库schooldemo下,使用SQL 语句建立关系数据库表:人员表PERSON(Pno,Pname, Page),房间表ROOM(Rno,Rname,Rarea), 表PR(Pno,Rno,Date).其中,表PERSON :Pno(CHAR(8),主码,非空,唯一),Pname(CHAR(20),非空),Page(INT);表ROOM:Rno(CHAR(8),主码,非空,唯一),Rname(CHAR(20)),Rarea(FLOAT(10));表PR:Pno(CHAR(8),非空,唯一),Rno(CHAR(8),非空,唯一),Date(DATETIME);(三个表之间有联系)create table person(pno char (8)primary key,pname char (20),page int);create table room(rno char (8) primary key,rname char(20),rarea float(10));create table pr(pno char (8),rno char (8),date datetime,primary key(pno,rno),foreign key(pno) references person(pno),foreign key(rno) references room(rno));3、更改基本表的定义,增加列,删除列,修改列的数据类型。
实验3 使用T-SQL语言完成单表查询一、实验目的掌握使用T—SQL语言完成单表查询掌握常用谓词的用法掌握where子句的用法掌握order by 子句的用法掌握group by 子句和having短语的用法二、实验环境Microsoft SQL Server 2000。
三、实验内容和要求1.查询全体学生的详细信息。
2.查询所有课程的详细信息.3.查询所有选课记录的详细信息,要结果表中的列名以中文的形式显示,分别为:学号,课程号,成绩。
4.查询已被学生选修了的课程的编号。
5.查询系别编号为“d002”的学生的姓名和性别。
6.查询年龄在19至21岁或者性别为“女”的学生的学号和所在系别编号。
7.查询系别编号为d001、d002和d003的学生的学号和姓名。
8.查询课程名为“C_”开头的课程名和学分.9.某些学生入学后还没有确定所在的系,查询还没有确定系的学生的姓名。
10.查询成绩大于60分的学生的学号、课程号和成绩,并将查询结果按课程编号升序排列,同一课程的成绩按分数降序排列。
11.查询学校所开设的总的课程数.12.计算2号课的学生成绩总和以及平均成绩,对应的列名分别为“总成绩”和“平均成绩”。
13.查询选修了3号课程的学生的最高分和最低分,对应的列名分别为“最高分”和“最低分"。
14.求各个系别的编号以及各系的人数。
15.查询选课人数大于等于2人的课程编号以及选课的人数。
16.查询学生200215122选修课程的总成绩对应的列名为“总成绩”,并显示出学号。
17.查询有2门以上课程是80分以上的学生的学号及课程数。
18.查询选修了1号课的学生的学号和成绩,结果按成绩降序、学号升序排列.实验1 使用T-SQL语言建库、建表实验2 向表中增、删、改数据四、实验目的掌握使用T-SQL建库、建表、修改表;掌握使用T-SQL对表中数据进行插入、删除和修改.五、实验环境Microsoft SQL Server 2000.六、实验内容和要求19.建立数据库STDB20.在数据库STDB中建立四个表:Student表Department表Course表21.分别向以上四个表中增加数据。
一、存储过程1. 创建存储过程,使用Employees表中的员工人数来初始化一个局部变量,并调用这个存储过程。
CREATE PROCEDURE TEST@NUMBER1INT OUTPUTASBEGINDECLARE@NUMBER2INTSET@NUMBER2=(SELECT COUNT(*)FROM Employees)SET@NUMBER1=@NUMBER2END执行该存储过程,查看结果。
DECLARE@num INTEXEC TEST@num OUTPUTSELECT@num2. 创建存储过程,比较两个员工的实际收入,若前者比后者高就输出1,否则就输出0。
CREATE PROCEDURE COMPA@ID1char(6),@ID2char(6),@BJ int OUTPUTASBEGINDECLARE@SR1float,@SR2floatSET@SR1=(SELECT InCome-OutCome FROM Salary WHERE EmployeeID=@ID1) SET@SR2=(SELECT InCome-OutCome FROM Salary WHERE EmployeeID=@ID2) IF@SR1>@SR2SET@BJ=1ELSESET@BJ=0END执行该存储过程,查看结果。
DECLARE@BJ intEXEC COMPA'504209','302566',@BJ OUTPUTSELECT@BJ3. 创建添加职员记录的存储过程EmployeeAdd。
CREATE PROCEDURE EmployeeADD(@employeeid char(6),@name char(10),@education char(4),@birthday datetime,@workyear tinyint,@sex bit,@address char(40),@phonenumber char(12), @departmentID char(3))ASBEGININSERT INTO EmployeesVALUES(@employeeid,@name,@education,@birthday,@workyear,@sex,@address,@phonenumber,@departmentID)ENDRETURNGO执行该存储过程。
SQL实验实验41.用select 语句查询departments和salary表中的所有数据:select salary.*, departments.*from salary ,departments2、查询departments 中的departmentid:select departmentid from departmentsgo3、查询 salary中的 income,outcome:select income,outcome from salarygo4、查询employees表中的部门号,性别,要用distinct消除重复行:select distinct(departmentid), sexfrom employees5、查询月收入高于2000元的员工号码:select employeeid from salarywhere income>2000go6、查询1970年以后出生的员工的姓名和住址:select name,addressfrom employeeswhere birthday>1970go7、查询所有财务部的员工的号码和姓名:select employeeid ,namefrom employeeswhere departmentid in(select departmentid from departments where departmentname='财务部')go8、查询employees员工的姓名,住址和收入水平,2000元以下显示为低收入,2000~3000元显示为中等收入,3000元以上显示为高收入:select name,address,casewhen income-outcome<2000 then'低收入'when income-outcome>3000 then'高收入'else'中等收入'end as'收入等级'from employees,salarywhere employees.employeeid=salary.employeeidgo9、计算salary表中员工月收入的评价数:select avg(income)as'平均收入'from salary10、查找employees表中最大的员工号码:select max(employeeid)as'最大员工号码'from employees11、计算salary表中的所有员工的总支出:select sum(outcome)as'总支出'from salary12、查询财务部雇员的最高实际收入:select max(income-outcome)from salary ,employees,departmentswhere salary.employeeid=employees.employeeid andemployees.departmentid=departments.departmentid and departmentname='财务部'13、查询财务部雇员的最低实际收入:select min(income-outcome)from salary ,employees,departmentswhere salary.employeeid=employees.employeeid andemployees.departmentid=departments.departmentid and departmentname='财务部' go14、找出所用地址中含有“中山”的雇员的号码及部门号:select employeeid ,departmentidfrom employeeswhere address like'%中山%'go15、查找员工号码中倒数第二个数字为0的员工的姓名,地址和学历:select education,address,namefrom employeeswhere employeeid like'%0_'go16、使用into字句,由表employees创建“男员工1”表,包括编号和姓名:select employeeid,nameinto男员工表from employeeswhere sex='1'go17、用子查询的方法查找收入在2500元以下的雇员的情况:select*from employeeswhere employeeid in(select employeeid from salary where income<2500)18、用子查询的方法查找查找研发部比所有财务部雇员收入都高的雇员的姓名:SELECT Name FROM Employees WHERE EmployeeID IN(SELECT EmployeeID FROM SalaryWHERE EmployeeID IN(SELECT EmployeeId FROM EmployeesWHERE DepartmentID IN(SELECT DepartmentID FROM DepartmentsWHERE DepartmentName='研发部'))AND InCome>ALL(SELECT InCome FROM SalaryWHERE EmployeeID IN(SELECT EmployeeId FROM EmployeesWHERE DepartmentID IN(SELECT DepartmentID FROM DepartmentsWHERE DepartmentName='财务部'))))19、用子查询的方法查找所有年龄比研发部雇员都大的雇员的姓名:select namefrom employeeswhere Birthday<all(select birthdayfrom employeeswhere departmentid in(select departmentidfrom departmentswhere departmentname='研发部')20、查询每个员工的情况及其薪水的情况:select employees.*,departments.departmentnamefrom employees,departmentswhere employees.departmentid=departments.departmentid21、使用内连接方法查找不在财务部工作的所有员工信息:select employees.*from employees inner join departments onemployees.departmentid=departments.departmentidwhere departmentname!='财务部'22、使用外连接方法查找出所有员工的月收入:select employees.*,salary.incomefrom employees join salary on employees.employeeid=salary.employeeid23、查找财务部雇员的最高收入:select max(income)from salarywhere employeeid in(select employeeidfrom employeeswhere departmentid in(select departmentidfrom departmentswhere departmentname='财务部'))24、查询财务部雇员的最高实际收入:select max(income-outcome)from salarywhere employeeid in(select employeeidfrom employeeswhere departmentid in(select departmentidfrom departmentswhere departmentname='财务部'))25、统计财务部收入在2500元以上的雇员人数:select count(employeeid)from employeeswhere departmentid in(select departmentid from departmentswhere departmentname='财务部')and employeeid in(select employeeidfrom salarywhere income>2500)26、按部门列出在该部门工作的员工的人数:select departmentid ,count(*)as人数from employeesgroup by departmentid27、按员工的学历分组:select education ,count(*)as人数from employeesgroup by education28、按员工的工作年份分组,统计年份人数:select workyear ,count(*)as人数from employeesgroup by workyear29、按各雇员的情况收入由低到高排列:select employees.*,salary.incomefrom employees ,salarywhere employees.employeeid=salary.employeeidorder by income30、将员工信息按出生时间从小到大排列:select*from employeesorder by birthday31、在order by 字句中使用子查询,查询员工姓名,性别和工龄信息,要求按实际收入从大到小排列:select name,sex,workyear,income-outcomefrom salary ,employeeswhere salary.employeeid=employees.employeeidorder by income-outcome desc视图部分1、创建view1:Create view view1asselect employees.employeeid,name,departmentname,(income-outcome)as comefrom employees , departments , salarywhere employees.departmentid=departments.departmentid and employees.employeeid=salary.employeeid2、查询视图employeeid:3、向视图view1中插入一行数据:insert into view1 values('111111','谎言','1','30000')4、查看视图(没有影响)基本表:实验51、定义一个变量,用于描述YGGL数据库的salary表中000001号员工的实际收入,然后查询该变量:declare @hy intset @hy=(select income-outcomefrom salarywhere employeeid='000001')select @hy2、使用运算符“>”:select namefrom employeeswhere birthday>'1974-10-10'3、判断姓名为“王林”的员工实际收入是否高于3000元,如果是则显示“高收入”,否则显示“收入不高于3000”:if((select incomefrom salary,employeeswhere salary.employeeid=employees.employeeid and ='刘明')>3000)select income as'高收入'from salary,employeeswhere salary.employeeid=employees.employeeid and ='刘明'elseselect'收入不高于'4、使用循环输出一个“*”三角形:declare @i intdeclare @j intset @j=20set @i=1while @i<@jbeginprint(space((@j-@i)/2)+replicate('*',@i))set @i=@i+2end4、按部门进行分类,使用if语句实现:Create function hy1(@departmentid1 char(3))returns char(10)asbegindeclare @hy1 char(10)if((select departmentid from departments where @departmentid1=departmentid)='1') set @hy1='财务部'if((select departmentid from departments where @departmentid1=departmentid)='2') set @hy1='人力资源部'if((select departmentid from departments where @departmentid1=departmentid)='3') set @hy1='经理办公室'if((select departmentid from departments where @departmentid1=departmentid)='4') set @hy1='研发部'if((select departmentid from departments where @departmentid1=departmentid)='5') set @hy1='市场部'return @hy1endselect employeeid,name,address,dbo.hy1(departmentid)from employeesselect employeeid,name,address,case departmentidwhen 1 then'财务部'when 2 then'人力资源部'when 3 then'经理办公室'when 4 then'研发部'when 5 then'市场部'end as部门号from employees6、自定义一个函数,计算一个数的阶层:create function hy(@hy2 int)returns int asbegindeclare @i intset @i=@hy2declare @j intset @j=1while @i>1beginset @j=@j*@iset @i=@i-1endreturn(@j)enddeclare @h intexec @h=dbo.hy 4select @h as'jiecheng'7、/*生成随机数*/select rand()8、/*平方*/select square(12)9、/*求财务部收入最高的员工姓名*/ select max(name)from employeeswhere employeeid in(select employeeidfrom salarywhere employeeid in(select employeeidfrom employeeswhere departmentid in(select departmentidfrom departmentswhere departmentname='财务部')))select avg(income)as'平均收入' from salary/*聚合函数与group by 一起使用*/ select workyear ,count(*)as人数from employeesgroup by workyear/*将字符组成字符串*/select char(123)/*返回字符串左边开始的个字符*/ select left('abcdef',2)/*返回指定日期时间的天数*/select day(birthday)from employeeswhere employeeid='010000'/*获取当前时间*/select getdate()实验61、创建索引:create unique index huangyanon employees(employeeid)2、/*用create index 语句创建主键*/3、重建表employees中employeeid列上的索引alter index huangyanon employees rebuild4、删除索引:5、创建一个新表,使用一个复合列作为主键,作为表的约束,并为其命名:create table employees5( employeeid char(6)not null,name char(5)not null,sex tinyint,education char(4),constraint yan primary key(employeeid,name))为新表添加一列:alter table employees5add address char(10)6、创建新表student,性别只能包含男或女:create table student(号码char(6)not null,性别char(2)not nullcheck(性别in('男','女')))7、创建新表:create table employees7(学号char(10)not null,出生日期datetime not nullcheck(出生日期>'1980-01-01'))8、创建一个规则:9,创建salary2:create table salary2(employeeid char(6)not null primary key,income float not null,outcome float not null,foreign key(employeeid)references salary(employeeid)on update cascadeon delete cascade)10、添加一个外键,salary与employees有相关记录,则拒绝更新employees:alter table salaryadd constraint kc_forforeign key(employeeid)references employees(employeeid)on delete no actionon update no action实验71、工作年份大于6时,跟换科室到经理办公室(根据员工):Create PROC UpdateDeptByYear(@EmpId char(6))ASBEGINDECLARE @year intSELECT @year=WorkYear From Employees WHERE EmployeeID=@EmpId IF(@year>6)UPDATE EmployeesSET DepartmentID='3'WHERE EmployeeID=@EmpIdENDEXEC UpdateDeptByYear '020010'SELECT*FROM Employees WHERE Employeeid='020010'2、根据每个员工的学历将收入提高元:CREATE PROC UpdateInComeByEdu @Employeeid char(6)ASBEGINUPDATE SalarySET InCome=InCome+500FROM SalaryLEFT JOIN EmployeesON Salary.EmployeeID=Employees.EmployeeIDWHERE Salary.Employeeid=@EmployeeidENDEXEC UpdateInComeByEdu '020010'SELECT*FROM Salary where EmployeeID='020010'3、游标:CREATE PROCEDURE Employees_biliASBEGINDECLARE @i FLOATDECLARE @j FLOATDECLARE @Education CHAR(10)DECLARE Employees_cursor CURSORFOR SELECT Education FROM EmployeesSET @i=0SET @j=0OPEN Employees_cursorFETCH Employees_cursor INTO @EducationWHILE(@@FETCH_STATUS=0)BEGINIF(@Education!='大专')SET @i=@i+1SET @j=@j+1FETCH Employees_cursor INTO @EducationENDCLOSE Employees_cursorSELECT @i AS'本科及以上员工所占员工数' SELECT @j AS'员工总数'SELECT @i/@j AS'本科及以上员工所占比例'CLOSE Employees_cursorENDEXEC Employees_bili4、使用命令的方式修改存储过程的定义:5、对于YGGL数据库,表Employees的EmployeeID列与表Salary的EmployeeID列应该满足参照的完整性规则,请用触发器实现两个表的参照完整性:CREATE TRIGGER Salary_insert ON SalaryFOR INSERT,UPDATEASBEGINIF(SELECT EmployeeID FROM INSERTED)NOT IN(SELECT EmployeeID FROM Employees) ROLLBACKENDCREATE TRIGGER Employeesupdate ON EmployeesFOR UPDATEASBEGINUPDATE SalarySET EmployeeID=(SELECT EmployeeID FROM INSERTED)WHERE EmployeeID=(SELECT EmployeeID FROM DELETED)ENDCREATE TRIGGER Employeesdelete ON EmployeesFOR DELETEASBEGINDELETE FROM SalaryWHERE EmployeeID=(SELECT EmployeeID FROM DELETED)ENDINSERT INTO SalaryVALUES('000005',2000,1000)UPDATE EmployeesSET EmployeeID='000000'WHERE EmployeeID='990230'DELETE FROM EmployeesWHERE EmployeeID='000000'6.当修改表Employees时,若将Employees表中员工的工作时间增加1年,则将收入增加500,若增加2年则增加1000,依次增加。