【SQL Server】存储过程

如何创建存储过程

定义存储过程的语法
CREATE PROC[EDURE] 存过过程名
@参数1 数据类型 = 默认值 OUTPUT,
… …,
@参数n 数据类型 = 默认值 OUTPUT,
AS
SQL语句
GO

存储过程的参数

  • 和C#语言的方法一样,参数可选。
  • 参数分为输入参数、输出参数。
  • 输入参数允许有默认值。

存储过程示例

Students表
这里写图片描述
ScoreLIst表
这里写图片描述
根据所给的CSharp和DB的分数筛选数据
带输入参数的存储过程

use StudentManager
go
if exists(select * from sysobjects where name ='usp_ScoreQuery2')
drop procedure usp_ScoreQuery2
go
--创建带参数的存储过程
create procedure usp_ScoreQuery2
@CSharp int,
@DB int 
as 
    select Students.StudentId,StudentName,CSharp ,SQLServerDB from Students 
    inner join ScoreList on Students.StudentId = ScoreList.StudentId
    where CSharp <@CSharp or SQLServerDB<@DB
go
--调用带参数的存储过程
exec usp_ScoreQuery2 60,65 --按照参数顺序赋值

根据所给的CSharp和DB的分数筛选数据,记录缺考人数和不及格人数
带输入参数和输出参数的存储过程

use StudentManager
go
if exists(select * from sysobjects where name ='usp_ScoreQuery3')
drop procedure usp_ScoreQuery3
go
--创建带参数的存储过程
create procedure usp_ScoreQuery3
--out一般写在输入参数之前
@ASentCount int output,--缺考人数
@FailedCount int output,--不及格总人数
@CSharp int=60,
@DB int=60 
as 
    select Students.StudentId,StudentName,CSharp ,SQLServerDB from Students 
    inner join ScoreList on Students.StudentId = ScoreList.StudentId
    where CSharp <@CSharp or SQLServerDB<@DB

    --查询统计结果
    select @ASentCount=count(*) from Students
    where StudentId not in (Select StudentId from ScoreList) --查询缺考的人数
    select @FailedCount=count(*) from ScoreList
    where CSharp<@CSharp or SQLServerDB<@DB --查询不及格的总人数

go
--调用带输出参数的存储过程
declare @ASentCount int,@FailedCount int --首先定义输出参数
exec usp_ScoreQuery3 @ASentCount output,@FailedCount output
select @ASentCount 缺考人数,@FailedCount 不及格人数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maybe_ch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值