SQL SERVER 之自定义函数(标量、表值)

我这人不喜欢写一些理论知识,我就简单粗暴直接上代码

创建表请访问:https://blog.csdn.net/Stodger0216/article/details/102840744,我就不再写创建表的代码了

标量:

/*创建标量函数*/
create function GetStuCount(@StuClass nvarchar(30), @StuSex nvarchar(10))
returns int
as
begin
	declare @StuCount int;
	if(@StuClass is not null and @StuClass <> '' and @StuSex is not null and @StuSex <> '')
		begin
			set @StuCount = (select count(*) from tb_student st where st.Sclass = @StuClass and st.Ssex = @StuSex);
		end
	else
		begin
			set @StuCount = 0;
		end
	return @StuCount;
end

/*执行标量函数*/
select dbo.GetStuCount('一班', '男') StuCount;

结果:

表值

/*创建表值函数*/
create function GetStuTotalAndAvg(@StuCourse nvarchar(30))
returns @returnTable table(
	Scourse nvarchar(30),
	Ssex nvarchar(10),
	courseTotal decimal(10,2),
	courseAvg decimal(10,2)
)
as
begin
	if(@StuCourse is not null and @StuCourse <> '')
		begin
			insert into @returnTable select sc.Scourse, st.Ssex, sum(sc.Sscore) courseTotal, avg(sc.Sscore) courseAvg from tb_student st, tb_score sc where sc.Scourse = @StuCourse and sc.Sno = st.Sno group by sc.Scourse,st.Ssex;
		end
	return
end

/*执行表值函数*/
select * from GetStuTotalAndAvg('数学');

结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值