存储过程

定义:能够完成一定功能或业务的sql代码,写在一块,形成一个特定功能的SQL代码集。
优点:模块化,提高代码的重用率,提高实行效率,降低了网络占用。
缺点:移植=>编译,调试
系统存储过程:sp_或xp_开头
sp_helptext=>显示存储过程的代码
sp_sqlexec=>执行sql字符
创建存储过程:
create proc/procedure Proc_存储名
@参数 数据类型=【默认值】-- 如果没有参数则省略参数
as
begin
sql语句
end
调用
exec proc/procedure Proc_存储名 @参数
删除
drop proc/procedure Proc_存储名 @参数
修改
alter proc/procedure Proc_存储名 @参数 数据类型=【默认值】-- 如果没有参数则省略参数
as
begin
sql语句
end
自定义存储过程
无参:
–创建 存储过程
create procedure Proc_Select_StudentInfo
as
begin
select * from StudentInfo
end
有参:
–创建
create proc proc_Select_Student_Gender
@sex bit
as
begin
select * from StudentInfo where Gender=@sex
end
go
–调用
exec proc_Select_Student_Gender 1
go

–修改
alter proc proc_Select_Student_Gender
@sex bit,
@CId int
as
begin
select * from StudentInfo where ClassId=@CId and Gender=@sex
end
go

exec proc_Select_Student_Gender 1,3
带输出参数:
Out 参数
–创建 带输出参数
create Proc proc_SetudentInfo_GetMaxAge
@mAge int out-- out 表示输出参数
as
begin
select @mAge=MAX(Age) from StudentInfo
end
go
– 调用
declare @maxAge int --定义一个变量,用于接收,存储过程中 的输出值

exec proc_SetudentInfo_GetMaxAge @maxAge out-- 传参时,也需要标明 该参数时,输出参数【out】

select @maxAge – 显示值
go
–output
create proc proc_Student_Demo
@param int output
as
begin
select @param=count(1) from StudentInfo where ClassId=@param
end
go

–调用
declare @cc int —定义一个变量,用于接收,存储过程中 的输出值
set @cc=1 —给参数赋值
exec proc_Student_Demo @cc output-- 传参时,也需要标明 该参数时,输出参数【output】

select @cc
select * from StudentInfo

–out 与output 区别
–相同:都是输出参数
–不同点:out 只能指明 输出参数 是谁,不能给输出参数 传值,
–output 可以赋值,而且在存储过程中当成变量来使用
带返回值:
create Proc proc_Student_GetFcount
as
begin
declare @result int
select @result= COUNT(1) from StudentInfo where Gender=0
return @result
end
go

—调用
declare @rs int
exec @rs=proc_Student_GetFcount
select @rs
go

带返回值 与 带输出参数 比较
带返回值: 只能有一个return,必须是一个标量
带输出参数:可以有多个输出参数 out,out

使用存储过程实现自增长
use StudDB
go
create table Deme
(
Id varchar(16) primary key not null,
Name varchar(10),
Discript Varchar(20)
)

create Proc Proc_Create_ID
@Id varchar(10) out
as
begin
declare @num int
select @Id=Id from Deme order by id --获取最后一条记录的ID
if(@Id is null)
begin
set @Id=‘s000000001’
end
else
begin
set @id=RIGHT(@id,9)
print @Id
set @num=CONVERT(int,@Id)
set @num=@num+1
set @Id=CONVERT(varchar(16),@num)
set @Id=‘0000000’+@Id
set @Id=‘s’+RIGHT(@Id,9)
end
end
go

declare @id varchar(16)
exec Proc_Create_ID @id out
insert into Deme values(@id,‘第一次执行’,‘测试’)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值