--例程9.9:创建一个存储过程,该存储过程能够实现根据系部的编号查询出系部中--男生、女生的人数,运行结果如图所示。USE studentsGOCREATEPROCEDURE proc_countsex @xbbh varchar(4)ASBEGINSELECT sex as'性别',count(id) as'人数合计'FROM studentWHEREsubstring(id,5,2)=@xbbhGROUP BY sexENDEXEC proc_countsex '02'--例程9.10 在students学生数据库中,创建一个存储过程proc_ testOutput,--要求实现返回成绩在@p1与@p3之间的学生人数,--其中,@p1与@p3是输入参数,用于指定分数段。CTEATE PROCEDURE dbo.proc_testOutput ( @p1 int , @p2 intOUTPUT, @p3 int ) ASBEGINselect @p2 =count(*) from stu where score between @p1 and @p3 RETURN @@rowcountPRINT @P2END--这个存储过程返回两个值,一个是output型参数@p2,调用存储过程后,返回结果存放在@p2中--另外一个是由return值@@rowcount(语句所影响的行数)
createproc cal_avg @sno char(10)asdeclare @score_avg numeric(3,0),@sid char(10)select @sid=sno from transcripts where sno=@snobeginif @sid isnullbeginprint'该学号不存在!'goto t_overendendselecttop3 score into #temp1 from transcripts where sno=@sno order by score descselect @score_avg=avg(score) from #temp1print'前三科平均成绩'print @score_avg t_over:
createproc findschool @startyear date,@endyear dateasdeclare @ schoolname char(20) , @num numeric(1,0)set @num=0declare findcursor cursorforselect schname from student, school, prizeinfo where student.schid=school.schid and student.sid= prizeinfo.sid and pyear between @startyear and @endyear group by schname order bycount(student.sid) descopen findcursor fetchnextfrom findcursor into @ schoolnamewhile @@fetch_status=0beginset @num =@num +1beginif @num >=3beginupdate school set remark=“最佳竞赛组织奖获得单位” where schname =@ schoolnamebreakendelseupdate school set remark=“最佳竞赛组织奖获得单位” where schname =@ schoolnameendfetchnextfrom findcursor into @ schoolname endclose findcursor deallocate findcursor--另外一种写法:createproc findschool @startyear date,@endyear dateAsupdate school set remark=“最佳竞赛组织奖获得单位” where schname in(selecttop3 schnamefrom student, school, prizeinfo where student.schid=school.schid and student.sid= prizeinfo.sid and pyear between @startyear and @endyear group by schname order bycount(student.sid) desc)