存储过程和函数

--存储过程:SQL语句和流程控制语句组成的预编译的代码块
create proc 存储过程名
@参数名 参数类型,
@参数名 参数类型
as
 存储过程体


--调用
exec 存储过程名 @值,@值

--范例:取款,
create proc sp_TakeMoney
@cardno varchar(19),
@money int
as
 declare @balance int
 --判断余额是否足够
 select @balance=余额字段 from 卡号信息表 where 卡号=@cardno
 if(@balance<@money)
  select 0
 else
 begin
  update 卡号信息表 set 余额字段=余额字段-@money
  where 卡号=@cardno
  select 1
 end

--函数(方法)
--分为:系统函数、自定义函数
/*特点:1、有返回值,所以根据返回值可以对自定义函数再次进行分类
  分为:标量值函数:返回结果为一个值,通常以SQL基本数据类型返回
     表值函数:返回结果为多个值,通常以表的形式返回
  2、函数返回的结果可以和其他SQL语句结合运行
  
语法:
create function 函数名(@参数 参数类型,@参数 参数类型)
returns 返回类型
as
begin
 函数体
end

调用:
select dbo.函数名(值,值)--标量函数
select * from dbo.函数名(值,值) --表值函数

--范例:
--标量函数(查询与最高分的学生同班的学生)
--查询最高分学生所在班级
create function getClassByMaxScore()
returns int
as
begin
 declare @class int
 select @class=class from scores where
 score=(select MAX(score) from scores)
 return @class
 
 --return(select class from scores where score=(select MAX(score) from scores))
end


--调用
select * from scores where class=dbo.getClassByMaxScore()


--表值函数
create function getmaxclassby()
returns @t table(id int,name varchar(20),score int,class int)
as
begin
 declare @class int
 select @class=class from scores where score=(select MAX(score) from scores)
 insert into @t select * from scores where class=@class
 return
end

select * from dbo.getmaxclassby()
*/

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值