--存储过程: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()
*/