【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 不及格人数

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/82499321