函数

时间:2019-11-11
本文章向大家介绍函数,主要包括函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1
--例8.2.1创建自定义标量函数TOTAL()用来计算任意两数之和。 2 create function total(@a int, @b int) 3 returns int 4 begin 5 declare @c int 6 select @c = @a + @b 7 return @c 8 end 9 --调用 10 select dbo.total(10, 20) 11 --例8.2.2编写一个函数,可以通过输入借书时间来判断是否到期,当借阅时间大于30天,返回已经过期;否则返回还未到期。 12 alter function isdateout(@a datetime) 13 returns varchar(20) 14 as 15 begin 16 declare @res varchar(20) 17 if (datediff(day, @a, getdate()) > 30) 18 set @res = '已过期' 19 else 20 set @res = '未到期' 21 return @res 22 end 23 --调用 24 select dbo.isdateout('2019-11-1') 25 --例8.2.3 创建标量函数sumstudent()统计选课学生总数。 26 create function cal() 27 returns int 28 begin 29 return (select count(distinct cno) from course) 30 end 31 --调用 32 print dbo.cal() 33 --例8.2.4 求选课表中某门课的平均成绩。 34 create function calavg(@cname char(4)) 35 returns float 36 as 37 begin 38 declare @res float 39 select @res = avg(grade) 40 from sc, course 41 where sc.cno = course.cno and course.cname = @cname 42 return @res 43 end 44 --调用 45 select dbo.calavg('英语') as 英语的平均成绩 46 --例8.2.5 创建函数fun_table( )返回一组查询的结果。 47 create function fun_table(@sno char(9), @grade int) 48 returns table 49 as 50 return 51 ( 52 select * 53 from sc 54 where sno = @sno and grade > @grade 55 ) 56 --调用 57 select * 58 from dbo.fun_table('200515001', 80) 59 --例8.2.6 查询某个专业所有学生的学号、姓名、所选课程的课程号和成绩。 60 alter function show(@major char(10)) 61 returns table 62 as 63 return 64 ( 65 select student.sno 学号, sname 姓名, cno 课程号, grade 成绩 66 from student, sc 67 where student.sno = sc.sno and sdept = @major 68 ) 69 70 select * 71 from dbo.show('cs') 72 --例8.2.7 查询计算机专业所有学生的学号、姓名、所选的课程号和成绩。 73 update dbo.show('cs') 74 set 姓名 = '张力' 75 where 学号 = '2005150033' 76 --????违反了 PRIMARY KEY 约束“PK_student”。不能在对象“dbo.student”中插入重复键。重复键值为 (200515001)。 77 --例8.2.8 创建函数fun_multi_table( )返回一个临时表。 78 create function fun_multi_table() 79 returns @tmp_table table(学号 char(9), 课程名 varchar(20), 成绩 int) 80 as 81 begin 82 insert @tmp_table 83 select sno, cname, grade 84 from sc, course 85 where sc.cno = course.cno 86 return 87 end 88 select * 89 from dbo.fun_multi_table() 90 --例8.2.9 创建多语句表值函数,通过学号作为实参调用该函数,可显示该学生的姓名以及各门功课的成绩和学分。 91 create function st_score(@no char(9)) 92 returns @score table(sno char(9), sname char(10), cname char(10), score int, credit int) 93 as 94 begin 95 insert @score 96 select s.sno, s.sname, c.cname, c.credit, sc.grade 97 from student s, course c, sc 98 where s.sno = sc.sno and c.cno = sc.cno and s.sno = @no 99 return 100 end 101 --调用 102 select * 103 from st_score('200515001')

原文地址:https://www.cnblogs.com/liuwenhan/p/11834106.html